-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
1868 lines (1746 loc) · 64.8 KB
/
Copy pathCode.gs
File metadata and controls
1868 lines (1746 loc) · 64.8 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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* OilPriceAPI Google Sheets add-on.
*
* Public listing: https://workspace.google.com/marketplace/app/oilpriceapi_for_google_sheets/991152473434
* Product facts: https://api.oilpriceapi.com/product-facts.json
*/
const API_BASE_URL = 'https://api.oilpriceapi.com/v1';
const ADDON_VERSION = '1.3.1';
const KEY_PROPERTY = 'OILPRICEAPI_KEY';
const LAST_DIAGNOSTIC_PROPERTY = 'OILPRICEAPI_LAST_DIAGNOSTIC';
const CACHE_GENERATION_PROPERTY = 'OILPRICEAPI_CACHE_GENERATION';
const MAX_BATCH_CODES = 25;
const PRICING_URL = 'https://www.oilpriceapi.com/pricing';
const SIGNUP_URL = 'https://www.oilpriceapi.com/auth/signup';
const MARKETPLACE_URL = 'https://workspace.google.com/marketplace/app/oilpriceapi_for_google_sheets/991152473434';
const CACHE_TTL_SECONDS = {
latest: 300,
latestFree: 3600,
latestEnterprise: 60,
generic: 300,
catalog: 21600,
bunker: 300,
exchangeRates: 3600,
history: 3600,
futures: 300,
rigCount: 3600
};
const MAX_CACHE_TTL_SECONDS = 21600;
let cachedGeneration_ = null;
let cachedCacheScope_ = null;
// Keep generic worksheet requests aligned with the Excel add-in's reviewed
// endpoint catalog. Add endpoints deliberately after API-shape tests exist.
const ENDPOINT_CATALOG = [
/^\/v1\/status$/,
/^\/v1\/prices$/,
/^\/v1\/prices\/latest$/,
/^\/v1\/prices\/past_day$/,
/^\/v1\/prices\/past_week$/,
/^\/v1\/prices\/past_month$/,
/^\/v1\/prices\/past_year$/,
/^\/v1\/prices\/historical$/,
/^\/v1\/prices\/all$/,
/^\/v1\/prices\/all\/health$/,
/^\/v1\/diesel-prices$/,
/^\/v1\/futures\/(ice-brent|ice-wti|ice-gasoil|natural-gas|eua-carbon)(\/(historical|ohlc|intraday|spreads|curve|spread-history))?$/,
/^\/v1\/commodities$/,
/^\/v1\/commodities\/categories$/,
/^\/v1\/commodities\/[A-Za-z0-9_.-]+$/
];
const SENSITIVE_QUERY_KEYS = new Set([
'accesstoken',
'apikey',
'authorization',
'auth',
'bearer',
'bearertoken',
'clientsecret',
'credential',
'credentials',
'key',
'password',
'secret',
'token',
'xapikey'
]);
const NUMERIC_FIELDS = new Set([
'open',
'high',
'low',
'close',
'settlement',
'settlement_price',
'last_price',
'price',
'spread_value',
'spread_percentage',
'front_price',
'back_price',
'change_percent',
'volume',
'open_interest'
]);
// Conversion support is intentionally narrower than API catalog access.
const COMMODITY_MAP = {
'BRENT_CRUDE_USD': { type: 'BRENT_CRUDE_OIL', unit: 'barrel' },
'WTI_USD': { type: 'WTI_CRUDE_OIL', unit: 'barrel' },
'NATURAL_GAS_USD': { type: 'NATURAL_GAS', unit: 'MBtu' },
'NATURAL_GAS_GBP': { type: 'NATURAL_GAS', unit: 'therm' },
'DUTCH_TTF_EUR': { type: 'NATURAL_GAS', unit: 'MWh' },
'COAL_USD': { type: 'COAL_BITUMINOUS', unit: 'tonne' },
'CAPP_COAL_USD': { type: 'COAL_BITUMINOUS', unit: 'short_ton' },
'PRB_COAL_USD': { type: 'COAL_BITUMINOUS', unit: 'short_ton' },
'ILLINOIS_COAL_USD': { type: 'COAL_BITUMINOUS', unit: 'short_ton' },
'NEWCASTLE_COAL_USD': { type: 'COAL_BITUMINOUS', unit: 'tonne' },
'COKING_COAL_USD': { type: 'COAL_BITUMINOUS', unit: 'tonne' },
'CME_COAL_USD': { type: 'COAL_BITUMINOUS', unit: 'short_ton' },
'NYMEX_APPALACHIAN_USD': { type: 'COAL_BITUMINOUS', unit: 'short_ton' },
'NYMEX_WESTERN_RAIL_USD': { type: 'COAL_BITUMINOUS', unit: 'short_ton' }
};
// Reference conversion factors. Verify suitability for the source dataset.
const HEAT_CONTENT = {
'BRENT_CRUDE_OIL': 5.8,
'WTI_CRUDE_OIL': 5.8,
'NATURAL_GAS': 1.037,
'COAL_BITUMINOUS': 24.0
};
function onOpen() {
const ui = SpreadsheetApp.getUi();
const menu = typeof ui.createAddonMenu === 'function'
? ui.createAddonMenu()
: ui.createMenu('OilPriceAPI');
menu
.addItem('Configure API Key', 'showSidebar')
.addItem('Fetch Latest Available Prices', 'showFetchDialog')
.addItem('Convert to $/MMBtu', 'convertToMBtu')
.addSeparator()
.addItem('Fetch Bunker Prices (Data Connector)', 'fetchDataConnectorPrices')
.addItem('Futures Formula Help', 'showFuturesInfo')
.addItem('Rig Count Formula Help', 'showRigCountInfo')
.addSeparator()
.addItem('About', 'showAbout')
.addToUi();
}
function onInstall(event) {
onOpen(event);
}
function showSidebar() {
const html = HtmlService.createHtmlOutputFromFile('Sidebar')
.setTitle('OilPriceAPI')
.setWidth(320);
SpreadsheetApp.getUi().showSidebar(html);
}
function showAbout() {
const ui = SpreadsheetApp.getUi();
ui.alert(
'OilPriceAPI for Google Sheets™',
`Runtime version: ${ADDON_VERSION}\n\n` +
'Source-timestamped energy price data. Dataset access and freshness vary.\n\n' +
'Available in Google Workspace Marketplace. The listing runtime is managed separately during staged releases.\n\n' +
`Install: ${MARKETPLACE_URL}\n\n` +
'Website: https://www.oilpriceapi.com\n' +
'Docs: https://docs.oilpriceapi.com',
ui.ButtonSet.OK
);
}
function getDocumentProperties_() {
try {
return PropertiesService.getDocumentProperties();
} catch (error) {
return null;
}
}
function getActiveSpreadsheetId_() {
try {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
return spreadsheet && typeof spreadsheet.getId === 'function'
? spreadsheet.getId()
: null;
} catch (error) {
return null;
}
}
function getSpreadsheetKeyProperty_() {
const spreadsheetId = getActiveSpreadsheetId_();
return spreadsheetId ? `${KEY_PROPERTY}:${spreadsheetId}` : null;
}
function getApiKey_() {
const documentProperties = getDocumentProperties_();
const documentKey = documentProperties
? documentProperties.getProperty(KEY_PROPERTY)
: null;
if (documentKey) return documentKey;
// Custom functions run in a distinct authorization context where Google can
// make document properties unavailable. User properties resolve to the
// spreadsheet owner in that context, so key the compatibility copy by the
// active spreadsheet ID to prevent credentials crossing between sheets.
const userProperties = PropertiesService.getUserProperties();
const spreadsheetKeyProperty = getSpreadsheetKeyProperty_();
const spreadsheetKey = spreadsheetKeyProperty
? userProperties.getProperty(spreadsheetKeyProperty)
: null;
return spreadsheetKey || null;
}
function requireApiKey_() {
const apiKey = getApiKey_();
if (!apiKey) {
throw makeError_('AUTH_REQUIRED', `Configure an API key from OilPriceAPI > Configure API Key, or create one at ${SIGNUP_URL}.`);
}
return apiKey;
}
function saveApiKey(apiKey) {
if (typeof apiKey !== 'string' || !apiKey.trim()) {
throw new Error('API key is required.');
}
const documentProperties = getDocumentProperties_();
if (!documentProperties) {
throw makeError_(
'ADDON_CONTEXT_REQUIRED',
'Open the OilPriceAPI sidebar from a Google Sheet before saving the API key.'
);
}
const spreadsheetKeyProperty = getSpreadsheetKeyProperty_();
if (!spreadsheetKeyProperty) {
throw makeError_(
'ADDON_CONTEXT_REQUIRED',
'Open the OilPriceAPI sidebar from a Google Sheet before saving the API key.'
);
}
documentProperties.setProperty(KEY_PROPERTY, apiKey.trim());
const previousGeneration = Number(documentProperties.getProperty(CACHE_GENERATION_PROPERTY));
const cacheGeneration = String(
Math.max(Date.now(), Number.isFinite(previousGeneration) ? previousGeneration + 1 : 0)
);
documentProperties.setProperty(CACHE_GENERATION_PROPERTY, cacheGeneration);
const userProperties = PropertiesService.getUserProperties();
userProperties.setProperty(spreadsheetKeyProperty, apiKey.trim());
userProperties.setProperty(`${CACHE_GENERATION_PROPERTY}:${getActiveSpreadsheetId_()}`, cacheGeneration);
userProperties.deleteProperty(KEY_PROPERTY);
cachedGeneration_ = null;
cachedCacheScope_ = null;
return {
success: true,
message: 'API key saved for this spreadsheet in Apps Script properties.'
};
}
function deleteApiKey() {
const documentProperties = getDocumentProperties_();
if (documentProperties) {
documentProperties.deleteProperty(KEY_PROPERTY);
documentProperties.deleteProperty(LAST_DIAGNOSTIC_PROPERTY);
documentProperties.deleteProperty(CACHE_GENERATION_PROPERTY);
}
const userProperties = PropertiesService.getUserProperties();
const spreadsheetKeyProperty = getSpreadsheetKeyProperty_();
if (spreadsheetKeyProperty) userProperties.deleteProperty(spreadsheetKeyProperty);
const spreadsheetId = getActiveSpreadsheetId_();
if (spreadsheetId) userProperties.deleteProperty(`${CACHE_GENERATION_PROPERTY}:${spreadsheetId}`);
userProperties.deleteProperty(KEY_PROPERTY);
userProperties.deleteProperty(LAST_DIAGNOSTIC_PROPERTY);
cachedGeneration_ = null;
cachedCacheScope_ = null;
return {
success: true,
message: 'Stored spreadsheet API key and request diagnostic deleted.'
};
}
function getApiKeyStatus() {
return { configured: Boolean(getApiKey_()) };
}
function normalizeCode_(value, label) {
const code = String(value || '').trim().toUpperCase();
if (!code) {
throw makeError_('INVALID_CODE', `${label || 'Code'} is required.`);
}
if (!/^[A-Z0-9_:-]+$/.test(code)) {
throw makeError_('INVALID_CODE', `${label || 'Code'} contains unsupported characters.`);
}
return code;
}
function makeError_(code, message) {
const error = new Error(message);
error.code = code;
return error;
}
function errorCode_(error) {
if (error && typeof error.code === 'string' && error.code) return error.code;
return 'ERROR';
}
function formulaError_(error) {
const message = error && typeof error.message === 'string' ? error.message : 'Unexpected error.';
return `#${errorCode_(error)}: ${message}`;
}
function formulaTableError_(error) {
const message = error && typeof error.message === 'string' ? error.message : 'Unexpected error.';
return [[`#${errorCode_(error)}`, message]];
}
function requestEndpoint_(path) {
const withoutQuery = String(path || '').split('?', 1)[0];
return withoutQuery.startsWith('/v1/') ? withoutQuery : `/v1${withoutQuery}`;
}
function responseHeader_(response, name) {
if (!response || typeof response.getHeaders !== 'function') return '';
const headers = response.getHeaders() || {};
const target = String(name).toLowerCase();
const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === target);
return key && typeof headers[key] === 'string' ? headers[key].slice(0, 128) : '';
}
function cacheContext_() {
if (cachedGeneration_ !== null && cachedCacheScope_ !== null) {
return { generation: cachedGeneration_, scope: cachedCacheScope_ };
}
const documentProperties = getDocumentProperties_();
const documentKey = documentProperties
? documentProperties.getProperty(KEY_PROPERTY)
: null;
const documentGeneration = documentProperties
? documentProperties.getProperty(CACHE_GENERATION_PROPERTY)
: null;
if (documentKey && documentGeneration && documentGeneration !== 'legacy') {
cachedGeneration_ = documentGeneration;
cachedCacheScope_ = 'document';
return { generation: cachedGeneration_, scope: cachedCacheScope_ };
}
const spreadsheetId = getActiveSpreadsheetId_();
let userGeneration = null;
if (spreadsheetId) {
try {
userGeneration = PropertiesService.getUserProperties().getProperty(
`${CACHE_GENERATION_PROPERTY}:${spreadsheetId}`
);
} catch (error) {
// Unknown credential contexts must remain isolated in the user cache.
}
}
cachedGeneration_ = userGeneration || 'legacy';
cachedCacheScope_ = 'user';
return { generation: cachedGeneration_, scope: cachedCacheScope_ };
}
function cacheGeneration_() {
return cacheContext_().generation;
}
function effectiveCacheScope_(requestedScope) {
if (requestedScope === 'user') return 'user';
return cacheContext_().scope;
}
function nextCacheGeneration_(previousGeneration) {
const previous = Number(previousGeneration);
return String(
Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)
);
}
function invalidateCacheGeneration_() {
const currentContext = cacheContext_();
const generation = nextCacheGeneration_(currentContext.generation);
let activeScopeInvalidated = false;
if (currentContext.scope === 'document') {
const documentProperties = getDocumentProperties_();
if (documentProperties) {
try {
documentProperties.setProperty(CACHE_GENERATION_PROPERTY, generation);
activeScopeInvalidated = true;
} catch (error) {
// A fallback generation cannot invalidate an active document cache.
}
}
}
const spreadsheetId = getActiveSpreadsheetId_();
if (spreadsheetId) {
try {
PropertiesService.getUserProperties().setProperty(
`${CACHE_GENERATION_PROPERTY}:${spreadsheetId}`,
generation
);
if (currentContext.scope === 'user') activeScopeInvalidated = true;
} catch (error) {
// A confirmed document write remains sufficient for document scope.
}
}
cachedGeneration_ = null;
cachedCacheScope_ = null;
if (!activeScopeInvalidated) {
throw makeError_(
'RETRY_LATER',
'Connection succeeded, but cached worksheet state could not be refreshed. Run Test Connection again.'
);
}
}
function stableCacheHash_(value) {
const text = String(value || '');
const digest = stableCacheDigest_(text);
const slug = text.replace(/[^A-Za-z0-9_-]+/g, '_').slice(0, 96);
return `${slug}_${digest}`;
}
function stableCacheDigest_(value) {
let hash = 2166136261;
const text = String(value || '');
for (let index = 0; index < text.length; index += 1) {
hash ^= text.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0).toString(36);
}
function combineCacheDigests_(primaryDigest, secondaryDigest) {
return `${primaryDigest}_${secondaryDigest}`;
}
function requestBlockKeys_(path) {
const endpoint = requestEndpoint_(path);
return {
global: 'request_block_global',
endpoint: `request_block_endpoint_${stableCacheHash_(endpoint)}`,
request: `request_block_request_${stableCacheHash_(String(path))}`
};
}
function cachedRequestBlock_(path) {
const keys = requestBlockKeys_(path);
for (const key of [keys.global, keys.endpoint, keys.request]) {
const blocked = getCachedValue_(key, MAX_CACHE_TTL_SECONDS, 'document');
if (blocked && typeof blocked.code === 'string' && typeof blocked.message === 'string') {
return blocked;
}
}
return null;
}
function clearRequestBlocks_(path) {
const keys = requestBlockKeys_(path);
for (const key of [keys.global, keys.endpoint, keys.request]) {
removeCachedValue_(key, 'document');
}
}
function retryWindowSeconds_(response, fallbackSeconds) {
const nowSeconds = Math.floor(Date.now() / 1000);
const reset = Number(responseHeader_(response, 'X-RateLimit-Reset'));
if (Number.isFinite(reset) && reset > nowSeconds) {
return Math.min(MAX_CACHE_TTL_SECONDS, Math.max(1, Math.ceil(reset - nowSeconds)));
}
const retryAfter = responseHeader_(response, 'Retry-After');
const numericRetry = Number(retryAfter);
if (Number.isFinite(numericRetry) && numericRetry > 0) {
const seconds = numericRetry > nowSeconds ? numericRetry - nowSeconds : numericRetry;
return Math.min(MAX_CACHE_TTL_SECONDS, Math.max(1, Math.ceil(seconds)));
}
const retryDate = new Date(retryAfter).getTime();
if (Number.isFinite(retryDate) && retryDate > Date.now()) {
return Math.min(
MAX_CACHE_TTL_SECONDS,
Math.max(1, Math.ceil((retryDate - Date.now()) / 1000))
);
}
return fallbackSeconds;
}
function responseMessage_(response) {
try {
const body = JSON.parse(response.getContentText());
const data = body && (body.data || body);
if (data && typeof data.message === 'string' && data.message.trim()) {
return data.message.trim().slice(0, 320);
}
} catch (error) {
// Use status-derived recovery text when the error body is unreadable.
}
return '';
}
function blockRequest_(path, statusCode, response, error) {
const keys = requestBlockKeys_(path);
let key = null;
let ttlSeconds = 0;
if (statusCode === 401) {
key = keys.global;
ttlSeconds = MAX_CACHE_TTL_SECONDS;
} else if (statusCode === 402) {
key = keys.global;
ttlSeconds = retryWindowSeconds_(response, MAX_CACHE_TTL_SECONDS);
} else if (statusCode === 429) {
key = keys.global;
ttlSeconds = retryWindowSeconds_(response, 60);
} else if (statusCode === 403) {
key = keys.endpoint;
ttlSeconds = MAX_CACHE_TTL_SECONDS;
} else if (statusCode === 404) {
key = keys.request;
ttlSeconds = 3600;
}
if (key && ttlSeconds > 0) {
putCachedValue_(
key,
{ code: error.code, message: error.message },
ttlSeconds,
'document'
);
}
}
function rememberResponseTier_(response) {
const tier = responseHeader_(response, 'X-RateLimit-Tier').trim().toLowerCase();
if (/^[a-z0-9_-]{1,32}$/.test(tier)) {
putCachedValue_('account_tier', tier, MAX_CACHE_TTL_SECONDS, 'document');
}
}
function latestCacheTtl_() {
const tier = getCachedValue_('account_tier', MAX_CACHE_TTL_SECONDS, 'document');
if (tier === 'free') return CACHE_TTL_SECONDS.latestFree;
if (tier === 'enterprise') return CACHE_TTL_SECONDS.latestEnterprise;
return CACHE_TTL_SECONDS.latest;
}
function persistDiagnostic_(input) {
try {
const diagnostic = {
schemaVersion: 1,
source: input.source || 'custom-function',
result: input.result || 'error',
code: input.code || 'ERROR',
endpoint: requestEndpoint_(input.endpoint || ''),
at: new Date().toISOString(),
durationMs: Math.max(0, Math.round(Number(input.durationMs) || 0))
};
if (Number.isInteger(input.httpStatus)) diagnostic.httpStatus = input.httpStatus;
if (typeof input.requestId === 'string' && input.requestId) {
diagnostic.requestId = input.requestId.slice(0, 128);
}
const properties = getDocumentProperties_() || PropertiesService.getUserProperties();
properties.setProperty(
LAST_DIAGNOSTIC_PROPERTY,
JSON.stringify(diagnostic)
);
} catch (error) {
// Diagnostics must never break a worksheet function.
}
}
function getLastDiagnostic() {
const properties = getDocumentProperties_() || PropertiesService.getUserProperties();
const raw = properties.getProperty(LAST_DIAGNOSTIC_PROPERTY);
if (!raw) return null;
try {
const value = JSON.parse(raw);
if (
!value ||
value.schemaVersion !== 1 ||
typeof value.code !== 'string' ||
typeof value.endpoint !== 'string' ||
typeof value.at !== 'string'
) {
return null;
}
return value;
} catch (error) {
return null;
}
}
function requestJson_(path, apiKey, options) {
const startedAt = Date.now();
const endpoint = requestEndpoint_(path);
const bypassBlock = options && options.bypassBlock === true;
if (!bypassBlock) {
const blocked = cachedRequestBlock_(path);
if (blocked) throw makeError_(blocked.code, blocked.message);
}
let response;
try {
const relativePath = String(path).startsWith('/v1/') ? String(path).slice(3) : String(path);
response = UrlFetchApp.fetch(`${API_BASE_URL}${relativePath}`, {
method: 'get',
headers: {
'Authorization': `Token ${apiKey}`,
'Accept': 'application/json',
// Apps Script locks User-Agent, so the server's client classifier is fed
// via X-API-Client instead (MinimalAnalyticsService.explicit_client_marker,
// which already maps oilpriceapi-google-sheets -> client_type
// 'sdk-google-sheets'). Without this, every call from this add-on lands as
// client_type 'unknown' and the add-on is invisible in adoption reporting.
// 285 users were sitting in 'unknown' when this was found. (#6167)
'X-API-Client': 'oilpriceapi-google-sheets',
'X-Client-Version': ADDON_VERSION
},
muteHttpExceptions: true
});
} catch (error) {
persistDiagnostic_({
result: 'timeout',
code: 'TIMEOUT',
endpoint,
durationMs: Date.now() - startedAt
});
throw makeError_('TIMEOUT', 'OilPriceAPI request failed or timed out. Retry later.');
}
const statusCode = response.getResponseCode();
const requestId = responseHeader_(response, 'x-request-id');
rememberResponseTier_(response);
if (statusCode === 401) {
const apiError = makeError_('AUTH_INVALID', `Invalid or revoked API key. Replace it from ${SIGNUP_URL}.`);
persistDiagnostic_({ result: 'http-error', code: 'AUTH_INVALID', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
blockRequest_(path, statusCode, response, apiError);
throw apiError;
}
if (statusCode === 402) {
const detail = responseMessage_(response);
const apiError = makeError_(
'UPGRADE_REQUIRED',
`${detail ? `${detail} ` : ''}Review or upgrade access at ${PRICING_URL}.`
);
persistDiagnostic_({ result: 'http-error', code: 'UPGRADE_REQUIRED', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
blockRequest_(path, statusCode, response, apiError);
throw apiError;
}
if (statusCode === 403) {
const apiError = makeError_('UPGRADE_REQUIRED', `This account cannot access the requested dataset. Review ${PRICING_URL}.`);
persistDiagnostic_({ result: 'http-error', code: 'UPGRADE_REQUIRED', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
blockRequest_(path, statusCode, response, apiError);
throw apiError;
}
if (statusCode === 429) {
const apiError = makeError_('RATE_LIMITED', 'OilPriceAPI rate or quota limit reached. Wait for the current limit window before retrying.');
persistDiagnostic_({ result: 'http-error', code: 'RATE_LIMITED', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
blockRequest_(path, statusCode, response, apiError);
throw apiError;
}
if (statusCode === 404) {
const apiError = makeError_('NO_DATA', 'The requested OilPriceAPI resource was not found. Check the code and endpoint.');
persistDiagnostic_({ result: 'http-error', code: 'NO_DATA', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
blockRequest_(path, statusCode, response, apiError);
throw apiError;
}
if (statusCode === 400 || statusCode === 422) {
let message = `OilPriceAPI rejected the request (HTTP ${statusCode}).`;
try {
const errorBody = JSON.parse(response.getContentText());
const errorData = errorBody && (errorBody.data || errorBody);
if (errorData && typeof errorData.message === 'string' && errorData.message.trim()) {
message = errorData.message.trim();
}
} catch (error) {
// Keep the status-derived message for an unreadable error body.
}
persistDiagnostic_({ result: 'http-error', code: 'INVALID_CODE', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
throw makeError_('INVALID_CODE', message);
}
if (statusCode >= 500) {
persistDiagnostic_({ result: 'http-error', code: 'SERVER_ERROR', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
throw makeError_('SERVER_ERROR', `OilPriceAPI is temporarily unavailable (HTTP ${statusCode}). Retry later.`);
}
if (statusCode !== 200) {
persistDiagnostic_({ result: 'http-error', code: 'ERROR', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
throw makeError_('ERROR', `OilPriceAPI request failed with HTTP ${statusCode}.`);
}
clearRequestBlocks_(path);
let body;
try {
body = JSON.parse(response.getContentText());
} catch (error) {
persistDiagnostic_({ result: 'invalid-response', code: 'INVALID_RESPONSE', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
throw makeError_('INVALID_RESPONSE', 'OilPriceAPI returned malformed JSON for a successful request.');
}
if (!body || typeof body !== 'object' || Array.isArray(body)) {
persistDiagnostic_({ result: 'invalid-response', code: 'INVALID_RESPONSE', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
throw makeError_('INVALID_RESPONSE', 'OilPriceAPI returned a non-object successful response.');
}
persistDiagnostic_({ result: 'success', code: 'OK', endpoint, durationMs: Date.now() - startedAt, httpStatus: statusCode, requestId });
return body;
}
function extractPriceRecords_(body, subject) {
const payload = body.data;
let records = null;
if (Array.isArray(payload)) {
records = payload;
} else if (payload && typeof payload === 'object') {
if (Array.isArray(payload.prices)) {
records = payload.prices;
} else if (payload.price && typeof payload.price === 'object') {
records = [payload.price];
} else if ('code' in payload || 'price' in payload) {
records = [payload];
}
}
if (!Array.isArray(records) || records.length === 0 || records.some((item) => !item || typeof item !== 'object')) {
throw makeError_('INVALID_RESPONSE', `OilPriceAPI returned no usable ${subject || 'price'} in a successful response.`);
}
return records;
}
function extractDataArray_(body, key, subject) {
const payload = body.data;
const records = payload && typeof payload === 'object' ? payload[key] : null;
if (!Array.isArray(records) || records.length === 0 || records.some((item) => !item || typeof item !== 'object')) {
throw makeError_('INVALID_RESPONSE', `OilPriceAPI returned no usable ${subject} in a successful response.`);
}
return records;
}
function sourceTimestamp_(record, subject) {
const timestamp = record.as_of || record.created_at || record.updated_at || record.timestamp || record.date || record.collected_at;
if (typeof timestamp !== 'string' || !timestamp.trim() || !Number.isFinite(new Date(timestamp).getTime())) {
throw makeError_('INVALID_RESPONSE', `${subject} is missing a valid source timestamp.`);
}
return timestamp;
}
function validatePriceRecord_(record, subject) {
const code = normalizeCode_(record.code || record.symbol, `${subject} code`);
const price = Number(record.price);
if (!Number.isFinite(price)) {
throw makeError_('INVALID_RESPONSE', `${subject} ${code} is missing a finite price.`);
}
if (typeof record.currency !== 'string' || !record.currency.trim()) {
throw makeError_('INVALID_RESPONSE', `${subject} ${code} is missing currency.`);
}
if (typeof record.unit !== 'string' || !record.unit.trim()) {
throw makeError_('INVALID_RESPONSE', `${subject} ${code} is missing unit.`);
}
return {
code,
price,
currency: record.currency.trim(),
unit: record.unit.trim(),
source: typeof record.source === 'string' ? record.source : '',
sourceDescription:
record.metadata && typeof record.metadata.source_description === 'string'
? record.metadata.source_description
: '',
timestamp: sourceTimestamp_(record, `${subject} ${code}`),
collectedAt: typeof record.collected_at === 'string' ? record.collected_at : '',
formatted: typeof record.formatted === 'string' ? record.formatted : '',
dataStatus:
typeof record.data_status === 'string'
? record.data_status
: record.freshness && typeof record.freshness.status === 'string'
? record.freshness.status
: '',
stale: typeof record.stale === 'boolean' ? record.stale : '',
ageDays: Number.isFinite(Number(record.age_days)) ? Number(record.age_days) : ''
};
}
function cacheStoreContext_(scope) {
if (typeof CacheService === 'undefined') return null;
const effectiveScope = effectiveCacheScope_(scope || 'document');
if (
effectiveScope === 'document' &&
typeof CacheService.getDocumentCache === 'function'
) {
try {
const documentCache = CacheService.getDocumentCache();
if (documentCache) return { store: documentCache, scope: 'document' };
} catch (error) {
// Fall through to the per-user cache when the document cache is unavailable.
}
}
try {
if (typeof CacheService.getUserCache !== 'function') return null;
const userCache = CacheService.getUserCache();
return userCache ? { store: userCache, scope: 'user' } : null;
} catch (error) {
return null;
}
}
function namespacedCacheKey_(cacheKey, cacheScope) {
if (cacheScope === 'user') {
const spreadsheetId = getActiveSpreadsheetId_();
if (!spreadsheetId) return null;
const spreadsheetHash = combineCacheDigests_(
stableCacheDigest_(spreadsheetId),
stableCacheDigest_(`sheet:${spreadsheetId}`)
);
return `opa_u_${spreadsheetHash}_${cacheGeneration_()}_${cacheKey}`;
}
return `opa_d_${cacheGeneration_()}_${cacheKey}`;
}
function getCachedValue_(cacheKey, maxAgeSeconds, scope) {
try {
const cacheContext = cacheStoreContext_(scope || 'document');
if (!cacheContext || typeof cacheContext.store.get !== 'function') return null;
const namespacedKey = namespacedCacheKey_(cacheKey, cacheContext.scope);
if (!namespacedKey) return null;
const raw = cacheContext.store.get(namespacedKey);
if (!raw) return null;
let envelope;
try {
envelope = JSON.parse(raw);
} catch (error) {
try {
cacheContext.store.remove(namespacedKey);
} catch (removeError) {
// An invalid entry can expire naturally if removal is unavailable.
}
return null;
}
if (
!envelope ||
typeof envelope.cachedAt !== 'number' ||
!Object.prototype.hasOwnProperty.call(envelope, 'value') ||
Date.now() - envelope.cachedAt > maxAgeSeconds * 1000
) {
try {
cacheContext.store.remove(namespacedKey);
} catch (removeError) {
// An expired entry can expire naturally if removal is unavailable.
}
return null;
}
return envelope.value;
} catch (error) {
// Cache failures must degrade to a live request.
return null;
}
}
function putCachedValue_(cacheKey, value, ttlSeconds, scope) {
try {
const cacheContext = cacheStoreContext_(scope || 'document');
if (!cacheContext || typeof cacheContext.store.put !== 'function') return;
const namespacedKey = namespacedCacheKey_(cacheKey, cacheContext.scope);
if (!namespacedKey) return;
cacheContext.store.put(
namespacedKey,
JSON.stringify({ cachedAt: Date.now(), value }),
Math.min(MAX_CACHE_TTL_SECONDS, Math.max(1, Math.round(ttlSeconds)))
);
} catch (error) {
// Cache limits or transient cache failures must not replace live API data.
}
}
function removeCachedValue_(cacheKey, scope) {
try {
const cacheContext = cacheStoreContext_(scope || 'document');
if (cacheContext && typeof cacheContext.store.remove === 'function') {
const namespacedKey = namespacedCacheKey_(cacheKey, cacheContext.scope);
if (namespacedKey) cacheContext.store.remove(namespacedKey);
}
} catch (error) {
// Request-block cleanup must not replace a valid live response.
}
}
function cacheMissLock_() {
if (
typeof LockService === 'undefined' ||
typeof LockService.getDocumentLock !== 'function'
) return null;
try {
return LockService.getDocumentLock();
} catch (error) {
return null;
}
}
function withCacheMissLock_(cacheKey, maxAgeSeconds, loader) {
const lock = cacheMissLock_();
if (!lock) return loader();
let acquired;
try {
acquired = lock.tryLock(5000);
} catch (error) {
return loader();
}
if (!acquired) {
const afterWait = getCachedValue_(cacheKey, maxAgeSeconds, 'document');
if (afterWait !== null) return afterWait;
throw makeError_(
'RETRY_LATER',
'Another sheet calculation is refreshing this value. Recalculate shortly.'
);
}
try {
const afterLock = getCachedValue_(cacheKey, maxAgeSeconds, 'document');
return afterLock !== null ? afterLock : loader();
} finally {
try {
lock.releaseLock();
} catch (error) {
// Releasing a transient service handle must not replace live data.
}
}
}
function cachedRequestJson_(cacheKey, path, ttlSeconds) {
const cached = getCachedValue_(cacheKey, ttlSeconds, 'document');
if (cached !== null) return cached;
return withCacheMissLock_(cacheKey, ttlSeconds, () => {
const body = requestJson_(path, requireApiKey_());
putCachedValue_(cacheKey, body, ttlSeconds, 'document');
return body;
});
}
function getLatestRecord_(commodityCode) {
const code = normalizeCode_(commodityCode, 'Commodity code');
const cacheKey = `latest_${code}`;
const ttlSeconds = latestCacheTtl_();
const cached = getCachedValue_(cacheKey, ttlSeconds, 'document');
if (cached) return cached;
return withCacheMissLock_(cacheKey, ttlSeconds, () => {
const body = requestJson_(`/prices/latest?by_code=${encodeURIComponent(code)}`, requireApiKey_());
let record;
try {
record = validatePriceRecord_(extractPriceRecords_(body, 'price')[0], 'Price record');
} catch (error) {
persistDiagnostic_({
result: 'invalid-response',
code: 'INVALID_RESPONSE',
endpoint: '/v1/prices/latest',
durationMs: 0,
httpStatus: 200
});
throw error;
}
putCachedValue_(cacheKey, record, latestCacheTtl_(), 'document');
return record;
});
}
function normalizeCodeRange_(values) {
const rows = Array.isArray(values) ? values : [values];
const flattened = [];
for (const row of rows) {
if (Array.isArray(row)) flattened.push(...row);
else flattened.push(row);
}
const codes = [];
for (const value of flattened) {
if (value === null || value === undefined || String(value).trim() === '') continue;
const code = normalizeCode_(value, 'Commodity code');
if (!codes.includes(code)) codes.push(code);
}
if (codes.length === 0) {
throw makeError_('INVALID_CODE', 'Select at least one commodity code.');
}
if (codes.length > MAX_BATCH_CODES) {
throw makeError_('INVALID_CODE', `Select at most ${MAX_BATCH_CODES} commodity codes.`);
}
return codes;
}
function readLatestRecordsFromCache_(codes, ttlSeconds) {
const records = new Map();
for (const code of codes) {
const record = getCachedValue_(`latest_${code}`, ttlSeconds, 'document');
if (record) records.set(code, record);
}
return records;
}
function getLatestRecords_(codes) {
let ttlSeconds = latestCacheTtl_();
let records = readLatestRecordsFromCache_(codes, ttlSeconds);
if (records.size === codes.length) return codes.map((code) => records.get(code));
let lock = cacheMissLock_();
let acquired = true;
if (lock) {
try {
acquired = lock.tryLock(5000);
} catch (error) {
lock = null;
}
}
if (!acquired) {
records = readLatestRecordsFromCache_(codes, latestCacheTtl_());
if (records.size === codes.length) return codes.map((code) => records.get(code));
throw makeError_(
'RETRY_LATER',
'Another sheet calculation is refreshing these values. Recalculate shortly.'
);
}
try {
ttlSeconds = latestCacheTtl_();
records = readLatestRecordsFromCache_(codes, ttlSeconds);