@haatlabs-core/providers 0.0.0-stage → 0.11.0

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.
Files changed (124) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -2
  3. package/dist/abort.d.ts +4 -0
  4. package/dist/abort.js +24 -0
  5. package/dist/abort.js.map +1 -0
  6. package/dist/cache/cached-call.d.ts +55 -0
  7. package/dist/cache/cached-call.js +212 -0
  8. package/dist/cache/cached-call.js.map +1 -0
  9. package/dist/cache/codecs.d.ts +11 -0
  10. package/dist/cache/codecs.js +33 -0
  11. package/dist/cache/codecs.js.map +1 -0
  12. package/dist/cache/hash.d.ts +2 -0
  13. package/dist/cache/hash.js +36 -0
  14. package/dist/cache/hash.js.map +1 -0
  15. package/dist/cache/index.d.ts +5 -0
  16. package/dist/cache/index.js +6 -0
  17. package/dist/cache/index.js.map +1 -0
  18. package/dist/cache/redis-store.d.ts +18 -0
  19. package/dist/cache/redis-store.js +73 -0
  20. package/dist/cache/redis-store.js.map +1 -0
  21. package/dist/cache/store.d.ts +29 -0
  22. package/dist/cache/store.js +86 -0
  23. package/dist/cache/store.js.map +1 -0
  24. package/dist/cache/ttl.d.ts +2 -0
  25. package/dist/cache/ttl.js +7 -0
  26. package/dist/cache/ttl.js.map +1 -0
  27. package/dist/cache.d.ts +1 -0
  28. package/dist/cache.js +2 -0
  29. package/dist/cache.js.map +1 -0
  30. package/dist/circuit-breaker.d.ts +29 -0
  31. package/dist/circuit-breaker.js +86 -0
  32. package/dist/circuit-breaker.js.map +1 -0
  33. package/dist/cjs/abort.d.ts +4 -0
  34. package/dist/cjs/abort.js +49 -0
  35. package/dist/cjs/cache/cached-call.d.ts +55 -0
  36. package/dist/cjs/cache/cached-call.js +205 -0
  37. package/dist/cjs/cache/codecs.d.ts +11 -0
  38. package/dist/cjs/cache/codecs.js +58 -0
  39. package/dist/cjs/cache/hash.d.ts +2 -0
  40. package/dist/cjs/cache/hash.js +56 -0
  41. package/dist/cjs/cache/index.d.ts +5 -0
  42. package/dist/cjs/cache/index.js +29 -0
  43. package/dist/cjs/cache/redis-store.d.ts +18 -0
  44. package/dist/cjs/cache/redis-store.js +88 -0
  45. package/dist/cjs/cache/store.d.ts +29 -0
  46. package/dist/cjs/cache/store.js +104 -0
  47. package/dist/cjs/cache/ttl.d.ts +2 -0
  48. package/dist/cjs/cache/ttl.js +31 -0
  49. package/dist/cjs/cache.d.ts +1 -0
  50. package/dist/cjs/cache.js +21 -0
  51. package/dist/cjs/circuit-breaker.d.ts +29 -0
  52. package/dist/cjs/circuit-breaker.js +101 -0
  53. package/dist/cjs/concurrency.d.ts +26 -0
  54. package/dist/cjs/concurrency.js +120 -0
  55. package/dist/cjs/errors.d.ts +14 -0
  56. package/dist/cjs/errors.js +38 -0
  57. package/dist/cjs/index.d.ts +16 -0
  58. package/dist/cjs/index.js +56 -0
  59. package/dist/cjs/package.json +3 -0
  60. package/dist/cjs/protect.d.ts +12 -0
  61. package/dist/cjs/protect.js +32 -0
  62. package/dist/cjs/retry-after.d.ts +8 -0
  63. package/dist/cjs/retry-after.js +49 -0
  64. package/dist/cjs/retry.d.ts +35 -0
  65. package/dist/cjs/retry.js +89 -0
  66. package/dist/cjs/safe-fetch/address.d.ts +7 -0
  67. package/dist/cjs/safe-fetch/address.js +55 -0
  68. package/dist/cjs/safe-fetch/errors.d.ts +17 -0
  69. package/dist/cjs/safe-fetch/errors.js +43 -0
  70. package/dist/cjs/safe-fetch/index.d.ts +7 -0
  71. package/dist/cjs/safe-fetch/index.js +44 -0
  72. package/dist/cjs/safe-fetch/safe-fetch.d.ts +103 -0
  73. package/dist/cjs/safe-fetch/safe-fetch.js +373 -0
  74. package/dist/cjs/safe-fetch/sniff.d.ts +6 -0
  75. package/dist/cjs/safe-fetch/sniff.js +49 -0
  76. package/dist/cjs/shared-call.d.ts +7 -0
  77. package/dist/cjs/shared-call.js +36 -0
  78. package/dist/cjs/shared-gateway.d.ts +88 -0
  79. package/dist/cjs/shared-gateway.js +171 -0
  80. package/dist/cjs/turns.d.ts +49 -0
  81. package/dist/cjs/turns.js +90 -0
  82. package/dist/concurrency.d.ts +26 -0
  83. package/dist/concurrency.js +111 -0
  84. package/dist/concurrency.js.map +1 -0
  85. package/dist/errors.d.ts +14 -0
  86. package/dist/errors.js +10 -0
  87. package/dist/errors.js.map +1 -0
  88. package/dist/index.d.ts +16 -0
  89. package/dist/index.js +19 -0
  90. package/dist/index.js.map +1 -0
  91. package/dist/protect.d.ts +12 -0
  92. package/dist/protect.js +11 -0
  93. package/dist/protect.js.map +1 -0
  94. package/dist/retry-after.d.ts +8 -0
  95. package/dist/retry-after.js +31 -0
  96. package/dist/retry-after.js.map +1 -0
  97. package/dist/retry.d.ts +35 -0
  98. package/dist/retry.js +68 -0
  99. package/dist/retry.js.map +1 -0
  100. package/dist/safe-fetch/address.d.ts +7 -0
  101. package/dist/safe-fetch/address.js +34 -0
  102. package/dist/safe-fetch/address.js.map +1 -0
  103. package/dist/safe-fetch/errors.d.ts +17 -0
  104. package/dist/safe-fetch/errors.js +19 -0
  105. package/dist/safe-fetch/errors.js.map +1 -0
  106. package/dist/safe-fetch/index.d.ts +7 -0
  107. package/dist/safe-fetch/index.js +5 -0
  108. package/dist/safe-fetch/index.js.map +1 -0
  109. package/dist/safe-fetch/safe-fetch.d.ts +103 -0
  110. package/dist/safe-fetch/safe-fetch.js +411 -0
  111. package/dist/safe-fetch/safe-fetch.js.map +1 -0
  112. package/dist/safe-fetch/sniff.d.ts +6 -0
  113. package/dist/safe-fetch/sniff.js +31 -0
  114. package/dist/safe-fetch/sniff.js.map +1 -0
  115. package/dist/shared-call.d.ts +7 -0
  116. package/dist/shared-call.js +17 -0
  117. package/dist/shared-call.js.map +1 -0
  118. package/dist/shared-gateway.d.ts +88 -0
  119. package/dist/shared-gateway.js +163 -0
  120. package/dist/shared-gateway.js.map +1 -0
  121. package/dist/turns.d.ts +49 -0
  122. package/dist/turns.js +84 -0
  123. package/dist/turns.js.map +1 -0
  124. package/package.json +87 -4
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Haatlabs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @haatlabs-core/providers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ What every caller of an outside service needs, written once: `retry`, a circuit breaker,
4
+ rate-limit turns, a concurrency limit and `mapLimit`, `protect` (the layers in their order),
5
+ the services-gateway contract (tiers and the headers a gateway reads), `cachedCall` with single-flight, and the safe fetch of
6
+ untrusted URLs (`@haatlabs-core/providers/safe-fetch`). Each takes any call; the error a project
7
+ throws stays the project's. It throws `PROVIDER_UNAVAILABLE` by default; a project spreads
8
+ `PROVIDERS_ERRORS` into `defineErrors`.
9
+
10
+ const breaker = createCircuitBreaker({ name: 'search' });
11
+ const gate = gateByRateLimit(limiter, { key: 'search', policy }, (ms) => refusal(ms));
12
+ const answer = await protect(() => call(), { gate, breaker, retry: { signal } });
13
+
14
+ The root carries `cachedCall`, the codecs and the memory store, never the Redis one: import
15
+ `createRedisCacheStore` from `@haatlabs-core/providers/cache`, so the root's types never name
16
+ `ioredis`. The root loads no HTTP client either; `sniffImageType` is there as well as in
17
+ `@haatlabs-core/providers/safe-fetch`.
18
+
19
+ A fetch that failed for now (DNS, a reset, a 5xx or 429 image) is worth another attempt:
20
+
21
+ import { isTransientSafeFetchError, safeFetchImage } from '@haatlabs-core/providers/safe-fetch';
22
+ const image = await retry(() => safeFetchImage(url, { signal }), {
23
+ isRetryable: isTransientSafeFetchError,
24
+ signal,
25
+ });
26
+
27
+ `localTimeoutMs(timeoutMs, call)` bounds an adapter's own timeout by the call's deadline, and
28
+ `retryAfterMsOf(response.headers)` reads a `Retry-After` (seconds or a date, at most 300 s).
29
+
30
+ ## Install
31
+
32
+ pnpm add @haatlabs-core/providers
33
+
34
+ It leaves one package to your app, so the app holds one copy: `ioredis`.
@@ -0,0 +1,4 @@
1
+ /** The caller's abort as an error: their reason if it is an Error, else an AbortError. */
2
+ export declare function abortError(signal: AbortSignal, what?: string): Error;
3
+ /** Waits `ms`, or rejects with the caller's abort as soon as `signal` aborts. */
4
+ export declare function abortableSleep(ms: number, signal?: AbortSignal): Promise<void>;
package/dist/abort.js ADDED
@@ -0,0 +1,24 @@
1
+ /** The caller's abort as an error: their reason if it is an Error, else an AbortError. */
2
+ export function abortError(signal, what = 'The call was aborted') {
3
+ const reason = signal.reason;
4
+ return reason instanceof Error ? reason : new DOMException(what, 'AbortError');
5
+ }
6
+ /** Waits `ms`, or rejects with the caller's abort as soon as `signal` aborts. */
7
+ export function abortableSleep(ms, signal) {
8
+ return new Promise((resolve, reject) => {
9
+ if (signal?.aborted) {
10
+ reject(abortError(signal));
11
+ return;
12
+ }
13
+ const onAbort = () => {
14
+ clearTimeout(handle);
15
+ reject(abortError(signal));
16
+ };
17
+ const handle = setTimeout(() => {
18
+ signal?.removeEventListener('abort', onAbort);
19
+ resolve();
20
+ }, ms);
21
+ signal?.addEventListener('abort', onAbort, { once: true });
22
+ });
23
+ }
24
+ //# sourceMappingURL=abort.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abort.js","sourceRoot":"","sources":["../src/abort.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,MAAM,UAAU,UAAU,CAAC,MAAmB,EAAE,IAAI,GAAG,sBAAsB;IAC3E,MAAM,MAAM,GAAY,MAAM,CAAC,MAAM,CAAC;IACtC,OAAO,MAAM,YAAY,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;AACjF,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,cAAc,CAAC,EAAU,EAAE,MAAoB;IAC7D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;YACpB,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;YAC3B,OAAO;QACT,CAAC;QACD,MAAM,OAAO,GAAG,GAAS,EAAE;YACzB,YAAY,CAAC,MAAM,CAAC,CAAC;YACrB,MAAM,CAAC,UAAU,CAAC,MAAqB,CAAC,CAAC,CAAC;QAC5C,CAAC,CAAC;QACF,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE;YAC7B,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9C,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,EAAE,CAAC,CAAC;QACP,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,55 @@
1
+ import type { Codec } from './codecs.js';
2
+ import { type CacheStore } from './store.js';
3
+ export type CacheEvent = 'hit' | 'miss' | 'joined' | 'store-error' | 'too-large';
4
+ /** 'hit': read from the store. 'miss': this caller computed. 'joined': another's compute was shared. */
5
+ export type CacheOutcome = 'hit' | 'miss' | 'joined';
6
+ export interface CachedResult<O> {
7
+ value: O;
8
+ /** `outcome !== 'miss'`. */
9
+ hit: boolean;
10
+ outcome: CacheOutcome;
11
+ /** When the value was computed (ms since the epoch). */
12
+ storedAt: number;
13
+ }
14
+ export type CachedCall<I, O> = (input: I, compute: () => Promise<O>) => Promise<CachedResult<O>>;
15
+ export interface CachedCallOptions<I, O> {
16
+ /** Null turns caching off: every call computes. */
17
+ store: CacheStore | null;
18
+ namespace: string;
19
+ /** A changed model, prompt or parser is a new version, never a stale hit. */
20
+ version: string | number;
21
+ ttlMs: number;
22
+ /** What identifies an answer: never a header, a key or the caller's identity. */
23
+ keyOf: (input: I) => unknown;
24
+ codec: Codec<O>;
25
+ /** A value it refuses is returned, not kept. */
26
+ cacheIf?: (value: O) => boolean;
27
+ /** Defaults: lockTtlMs 30 s, waitMs 10 s, pollMs 100 ms (at least 10). */
28
+ singleFlight?: {
29
+ lockTtlMs: number;
30
+ waitMs: number;
31
+ pollMs?: number;
32
+ };
33
+ /** How long a store that timed out is left alone, for every call on it. Default 10 s. */
34
+ storeAwayMs?: number;
35
+ /** For metrics. A 'store-error' comes with the error (the store's, or the codec's). */
36
+ onEvent?: (event: CacheEvent, detail?: {
37
+ error: unknown;
38
+ }) => void;
39
+ /** Test seams. */
40
+ now?: () => number;
41
+ sleep?: (ms: number) => Promise<void>;
42
+ }
43
+ /** The store key of an input: `${namespace}:v${version}:${hashKey(keyInput)}`. */
44
+ export declare const cacheKeyOf: (namespace: string, version: string | number, keyInput: unknown) => string;
45
+ /**
46
+ * A call whose answers are kept in `store` for `ttlMs`. Callers asking for the same key
47
+ * share one compute: in this process through one promise, across processes through the
48
+ * store's lock (the first takes it; the others look again every `pollMs` for up to `waitMs`,
49
+ * then compute themselves). A failed compute is thrown to the caller that ran it only and is
50
+ * never kept: whoever was waiting on it looks again and computes for itself, one at a time
51
+ * through the lock. A store that fails is a miss, never a failed call. A store that times out
52
+ * costs the call that found out one timeout only (no lock, no write after it), and is then
53
+ * left alone for `storeAwayMs` (10 s): calls compute directly.
54
+ */
55
+ export declare function cachedCall<I, O>(options: CachedCallOptions<I, O>): CachedCall<I, O>;
@@ -0,0 +1,212 @@
1
+ import { abortableSleep } from '../abort.js';
2
+ import { hashKey } from './hash.js';
3
+ import { isStoreTimeoutError } from './store.js';
4
+ const DEFAULT_LOCK_TTL_MS = 30_000;
5
+ const DEFAULT_WAIT_MS = 10_000;
6
+ const DEFAULT_POLL_MS = 100;
7
+ /** After a store times out, calls compute directly for this long. */
8
+ const DEFAULT_STORE_AWAY_MS = 10_000;
9
+ const MIN_POLL_MS = 10;
10
+ /**
11
+ * When a store that timed out is back in use, kept on the store itself so every cachedCall on it
12
+ * (from any copy of this package) shares the cool-off.
13
+ */
14
+ const AWAY_UNTIL = Symbol.for('@haatlabs-core/providers.cacheStoreAwayUntil');
15
+ /** Each entry starts with when it was computed, a float64. */
16
+ const STORED_AT_BYTES = 8;
17
+ /** The store key of an input: `${namespace}:v${version}:${hashKey(keyInput)}`. */
18
+ export const cacheKeyOf = (namespace, version, keyInput) => `${namespace}:v${version}:${hashKey(keyInput)}`;
19
+ /**
20
+ * A call whose answers are kept in `store` for `ttlMs`. Callers asking for the same key
21
+ * share one compute: in this process through one promise, across processes through the
22
+ * store's lock (the first takes it; the others look again every `pollMs` for up to `waitMs`,
23
+ * then compute themselves). A failed compute is thrown to the caller that ran it only and is
24
+ * never kept: whoever was waiting on it looks again and computes for itself, one at a time
25
+ * through the lock. A store that fails is a miss, never a failed call. A store that times out
26
+ * costs the call that found out one timeout only (no lock, no write after it), and is then
27
+ * left alone for `storeAwayMs` (10 s): calls compute directly.
28
+ */
29
+ export function cachedCall(options) {
30
+ const { store, codec } = options;
31
+ if (!options.namespace)
32
+ throw new Error('cachedCall needs a namespace');
33
+ if (!Number.isInteger(options.ttlMs) || options.ttlMs < 1) {
34
+ throw new RangeError('ttlMs must be a positive integer');
35
+ }
36
+ const positive = (name, value, least = 1) => {
37
+ if (!Number.isInteger(value) || value < least) {
38
+ throw new RangeError(`${name} must be an integer of at least ${least}`);
39
+ }
40
+ };
41
+ const now = options.now ?? Date.now;
42
+ const sleep = options.sleep ?? ((ms) => abortableSleep(ms));
43
+ const lockTtlMs = options.singleFlight?.lockTtlMs ?? DEFAULT_LOCK_TTL_MS;
44
+ const waitMs = options.singleFlight?.waitMs ?? DEFAULT_WAIT_MS;
45
+ const pollMs = options.singleFlight?.pollMs ?? DEFAULT_POLL_MS;
46
+ const inflight = new Map();
47
+ const emit = (event, detail) => {
48
+ try {
49
+ if (detail)
50
+ options.onEvent?.(event, detail);
51
+ else
52
+ options.onEvent?.(event);
53
+ }
54
+ catch {
55
+ // Counting is not what was asked for.
56
+ }
57
+ };
58
+ positive('lockTtlMs', lockTtlMs);
59
+ positive('waitMs', waitMs);
60
+ positive('pollMs', pollMs, MIN_POLL_MS);
61
+ const storeAwayMs = options.storeAwayMs ?? DEFAULT_STORE_AWAY_MS;
62
+ positive('storeAwayMs', storeAwayMs, 0);
63
+ const away = () => (store ? now() < (store[AWAY_UNTIL] ?? 0) : false);
64
+ /** Records a store failure; a timeout (from a store of any copy of this package) means away. */
65
+ const failed = (error) => {
66
+ emit('store-error', { error });
67
+ if (store && isStoreTimeoutError(error))
68
+ store[AWAY_UNTIL] = now() + storeAwayMs;
69
+ };
70
+ const read = async (key) => {
71
+ if (!store || away())
72
+ return null;
73
+ let bytes;
74
+ try {
75
+ bytes = await store.get(key);
76
+ }
77
+ catch (error) {
78
+ failed(error);
79
+ return null;
80
+ }
81
+ // Bytes it cannot read are a miss; the next write goes over them.
82
+ if (!bytes || bytes.length < STORED_AT_BYTES)
83
+ return null;
84
+ try {
85
+ return {
86
+ storedAt: bytes.readDoubleBE(0),
87
+ value: codec.decode(bytes.subarray(STORED_AT_BYTES)),
88
+ };
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ };
94
+ const write = async (key, found) => {
95
+ if (!store || away())
96
+ return;
97
+ let encoded;
98
+ try {
99
+ if (options.cacheIf && !options.cacheIf(found.value))
100
+ return;
101
+ encoded = codec.encode(found.value);
102
+ }
103
+ catch (error) {
104
+ emit('store-error', { error });
105
+ return;
106
+ }
107
+ const entry = Buffer.alloc(STORED_AT_BYTES + encoded.length);
108
+ entry.writeDoubleBE(found.storedAt, 0);
109
+ encoded.copy(entry, STORED_AT_BYTES);
110
+ if (store.maxValueBytes !== undefined && entry.length > store.maxValueBytes) {
111
+ emit('too-large');
112
+ return;
113
+ }
114
+ try {
115
+ await store.set(key, entry, options.ttlMs);
116
+ }
117
+ catch (error) {
118
+ failed(error);
119
+ }
120
+ };
121
+ const computeAndKeep = async (key, compute) => {
122
+ const value = await compute();
123
+ const found = { value, storedAt: now() };
124
+ await write(key, found);
125
+ return { found, outcome: 'miss' };
126
+ };
127
+ /** null: someone else holds it. undefined: the store has no lock, or it failed. */
128
+ const tryLock = async (key) => {
129
+ if (!store?.lock || away())
130
+ return undefined;
131
+ try {
132
+ return await store.lock(key, lockTtlMs);
133
+ }
134
+ catch (error) {
135
+ failed(error);
136
+ return undefined;
137
+ }
138
+ };
139
+ /** One caller's whole way to a value: the store, then the lock, then compute. */
140
+ const resolve = async (key, compute) => {
141
+ const cached = await read(key);
142
+ if (cached)
143
+ return { found: cached, outcome: 'hit' };
144
+ if (away())
145
+ return computeAndKeep(key, compute);
146
+ const startedAt = now();
147
+ for (;;) {
148
+ const release = await tryLock(key);
149
+ if (release === undefined)
150
+ return computeAndKeep(key, compute);
151
+ if (release) {
152
+ try {
153
+ // Another caller may have kept it between the read and the lock.
154
+ const kept = await read(key);
155
+ if (kept)
156
+ return { found: kept, outcome: 'joined' };
157
+ return await computeAndKeep(key, compute);
158
+ }
159
+ finally {
160
+ // Always released; but once the store is away, not waited for: a hung store would
161
+ // otherwise cost this call a second timeout.
162
+ const freeing = release().catch(failed);
163
+ if (!away())
164
+ await freeing;
165
+ }
166
+ }
167
+ if (now() - startedAt >= waitMs)
168
+ return computeAndKeep(key, compute);
169
+ await sleep(pollMs);
170
+ const shared = await read(key);
171
+ if (shared)
172
+ return { found: shared, outcome: 'joined' };
173
+ if (away())
174
+ return computeAndKeep(key, compute);
175
+ }
176
+ };
177
+ const done = (resolved) => {
178
+ emit(resolved.outcome);
179
+ return {
180
+ value: resolved.found.value,
181
+ storedAt: resolved.found.storedAt,
182
+ outcome: resolved.outcome,
183
+ hit: resolved.outcome !== 'miss',
184
+ };
185
+ };
186
+ return async (input, compute) => {
187
+ if (!store) {
188
+ const value = await compute();
189
+ emit('miss');
190
+ return { value, hit: false, outcome: 'miss', storedAt: now() };
191
+ }
192
+ const key = cacheKeyOf(options.namespace, options.version, options.keyOf(input));
193
+ const shared = inflight.get(key);
194
+ if (shared) {
195
+ const joined = await shared.catch(() => null);
196
+ if (joined)
197
+ return done({ found: joined.found, outcome: joined.outcome === 'hit' ? 'hit' : 'joined' });
198
+ // The compute it waited for failed: that failure was its caller's alone.
199
+ return done(await resolve(key, compute));
200
+ }
201
+ const own = resolve(key, compute);
202
+ inflight.set(key, own);
203
+ try {
204
+ return done(await own);
205
+ }
206
+ finally {
207
+ if (inflight.get(key) === own)
208
+ inflight.delete(key);
209
+ }
210
+ };
211
+ }
212
+ //# sourceMappingURL=cached-call.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cached-call.js","sourceRoot":"","sources":["../../src/cache/cached-call.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,mBAAmB,EAAmB,MAAM,YAAY,CAAC;AAwClE,MAAM,mBAAmB,GAAG,MAAM,CAAC;AACnC,MAAM,eAAe,GAAG,MAAM,CAAC;AAC/B,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,qEAAqE;AACrE,MAAM,qBAAqB,GAAG,MAAM,CAAC;AACrC,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB;;;GAGG;AACH,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;AAEzE,8DAA8D;AAC9D,MAAM,eAAe,GAAG,CAAC,CAAC;AAW1B,kFAAkF;AAClF,MAAM,CAAC,MAAM,UAAU,GAAG,CACxB,SAAiB,EACjB,OAAwB,EACxB,QAAiB,EACT,EAAE,CAAC,GAAG,SAAS,KAAK,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;AAE7D;;;;;;;;;GASG;AACH,MAAM,UAAU,UAAU,CAAO,OAAgC;IAC/D,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IACjC,IAAI,CAAC,OAAO,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CA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,MAAM,CAAC,GAAG,CAAC,CAAC;QACtD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ /** How a value is kept: as bytes. */
2
+ export interface Codec<T> {
3
+ encode(value: T): Buffer;
4
+ decode(bytes: Buffer): T;
5
+ }
6
+ /** JSON, checked on the way out by `parse` when given (a zod schema's `parse`, say). */
7
+ export declare function jsonCodec<T>(parse?: (value: unknown) => T): Codec<T>;
8
+ /** A vector as 32-bit floats: four bytes a dimension. */
9
+ export declare const float32Codec: Codec<number[]>;
10
+ /** The inner codec's bytes, gzipped: for values that repeat themselves (products, pages). */
11
+ export declare function gzipCodec<T>(inner: Codec<T>): Codec<T>;
@@ -0,0 +1,33 @@
1
+ import { gunzipSync, gzipSync } from 'node:zlib';
2
+ const BYTES_PER_FLOAT = 4;
3
+ /** The most a gzipped value may inflate to. */
4
+ const MAX_INFLATED_BYTES = 8 * 1024 * 1024;
5
+ /** JSON, checked on the way out by `parse` when given (a zod schema's `parse`, say). */
6
+ export function jsonCodec(parse) {
7
+ return {
8
+ encode: (value) => Buffer.from(JSON.stringify(value), 'utf8'),
9
+ decode: (bytes) => {
10
+ const value = JSON.parse(bytes.toString('utf8'));
11
+ return parse ? parse(value) : value;
12
+ },
13
+ };
14
+ }
15
+ /** A vector as 32-bit floats: four bytes a dimension. */
16
+ export const float32Codec = {
17
+ encode: (vector) => Buffer.from(new Float32Array(vector).buffer),
18
+ decode: (bytes) => {
19
+ if (bytes.length % BYTES_PER_FLOAT !== 0) {
20
+ throw new RangeError('A float32 vector is a whole number of four-byte values');
21
+ }
22
+ const copy = new Uint8Array(bytes);
23
+ return Array.from(new Float32Array(copy.buffer, 0, copy.length / BYTES_PER_FLOAT));
24
+ },
25
+ };
26
+ /** The inner codec's bytes, gzipped: for values that repeat themselves (products, pages). */
27
+ export function gzipCodec(inner) {
28
+ return {
29
+ encode: (value) => gzipSync(inner.encode(value)),
30
+ decode: (bytes) => inner.decode(gunzipSync(bytes, { maxOutputLength: MAX_INFLATED_BYTES })),
31
+ };
32
+ }
33
+ //# sourceMappingURL=codecs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codecs.js","sourceRoot":"","sources":["../../src/cache/codecs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAQjD,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,+CAA+C;AAC/C,MAAM,kBAAkB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAE3C,wFAAwF;AACxF,MAAM,UAAU,SAAS,CAAI,KAA6B;IACxD,OAAO;QACL,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAC7D,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YAChB,MAAM,KAAK,GAAY,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;YAC1D,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,KAAW,CAAC;QAC7C,CAAC;KACF,CAAC;AACJ,CAAC;AAED,yDAAyD;AACzD,MAAM,CAAC,MAAM,YAAY,GAAoB;IAC3C,MAAM,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC;IAChE,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;QAChB,IAAI,KAAK,CAAC,MAAM,GAAG,eAAe,KAAK,CAAC,EAAE,CAAC;YACzC,MAAM,IAAI,UAAU,CAAC,wDAAwD,CAAC,CAAC;QACjF,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;QACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,GAAG,eAAe,CAAC,CAAC,CAAC;IACrF,CAAC;CACF,CAAC;AAEF,6FAA6F;AAC7F,MAAM,UAAU,SAAS,CAAI,KAAe;IAC1C,OAAO;QACL,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAChD,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,eAAe,EAAE,kBAAkB,EAAE,CAAC,CAAC;KAC5F,CAAC;AACJ,CAAC"}
@@ -0,0 +1,2 @@
1
+ /** SHA-256 of the value's canonical JSON, base64url: the same input, the same key. */
2
+ export declare function hashKey(value: unknown): string;
@@ -0,0 +1,36 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** The value as JSON would write it, with object keys sorted and undefined fields left out. */
3
+ function canonical(value) {
4
+ // JSON would drop these, or write them as null, or throw: never a key of their own.
5
+ if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') {
6
+ throw new TypeError(`A cache key cannot hold a ${typeof value}`);
7
+ }
8
+ if (typeof value === 'number' && !Number.isFinite(value)) {
9
+ throw new TypeError('A cache key cannot hold NaN or Infinity');
10
+ }
11
+ if (value === null || typeof value !== 'object')
12
+ return value;
13
+ const withJson = value;
14
+ if (typeof withJson.toJSON === 'function')
15
+ return canonical(withJson.toJSON());
16
+ if (Array.isArray(value))
17
+ return value.map((item) => (item === undefined ? null : canonical(item)));
18
+ const prototype = Object.getPrototypeOf(value);
19
+ if (prototype !== Object.prototype && prototype !== null) {
20
+ throw new TypeError('A cache key holds plain objects, arrays and dates only');
21
+ }
22
+ const sorted = {};
23
+ for (const key of Object.keys(value).sort()) {
24
+ const item = value[key];
25
+ if (item !== undefined)
26
+ sorted[key] = canonical(item);
27
+ }
28
+ return sorted;
29
+ }
30
+ /** SHA-256 of the value's canonical JSON, base64url: the same input, the same key. */
31
+ export function hashKey(value) {
32
+ return createHash('sha256')
33
+ .update(JSON.stringify(canonical(value)) ?? 'undefined')
34
+ .digest('base64url');
35
+ }
36
+ //# sourceMappingURL=hash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../src/cache/hash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,+FAA+F;AAC/F,SAAS,SAAS,CAAC,KAAc;IAC/B,oFAAoF;IACpF,IAAI,OAAO,KAAK,KAAK,UAAU,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC1F,MAAM,IAAI,SAAS,CAAC,6BAA6B,OAAO,KAAK,EAAE,CAAC,CAAC;IACnE,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACzD,MAAM,IAAI,SAAS,CAAC,yCAAyC,CAAC,CAAC;IACjE,CAAC;IACD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,QAAQ,GAAG,KAAmC,CAAC;IACrD,IAAI,OAAO,QAAQ,CAAC,MAAM,KAAK,UAAU;QAAE,OAAO,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IAC/E,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACtB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,SAAS,GAAY,MAAM,CAAC,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