@open-mercato/cache-provider-infinispan 0.0.0-stage → 0.11.1-develop.9002.1.e180dacef1

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.
package/README.md CHANGED
@@ -1,3 +1,207 @@
1
- # Temporary Holding Version
1
+ # @open-mercato/cache-provider-infinispan
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
+ Open Mercato cache provider (`open-mercato/infinispan`) that stores the shared application cache in a **dedicated remote cache on an Infinispan Server** over Hot Rod. It plugs into the v1 cache-provider host of `@open-mercato/cache`; modules keep using the `cache` DI service, tenant scoping and tag invalidation unchanged.
4
+
5
+ Server-only. ESM with TypeScript types. Placement: `shared` when verified TLS is configured.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ yarn add @open-mercato/cache-provider-infinispan
11
+ ```
12
+
13
+ Peer dependency: `@open-mercato/cache` (>= 0.11.0). Runtime dependencies: the Apache-2.0 Hot Rod client [`infinispan`](https://www.npmjs.com/package/infinispan) (pinned to `0.16.3`, see [Client defects worked around](#client-defects-worked-around)) and `zod`. No other provider package or engine client is pulled in.
14
+
15
+ ## Prepare the server
16
+
17
+ Create a **dedicated** distributed cache for Open Mercato with `text/plain` encoding and **no eviction** (no `memory.max-count` / `max-size`; see [Limitations](#limitations)). Expiry is handled per entry by the provider.
18
+
19
+ ```json
20
+ {
21
+ "distributed-cache": {
22
+ "mode": "SYNC",
23
+ "owners": 2,
24
+ "statistics": true,
25
+ "encoding": { "media-type": "text/plain; charset=UTF-8" }
26
+ }
27
+ }
28
+ ```
29
+
30
+ For example `POST /rest/v2/caches/open-mercato` with that body, the CLI (`create cache --file=...`) or a server configuration file. Give the application user read/write permissions on that cache only.
31
+
32
+ ## Register and select
33
+
34
+ Add the registration to the app's `src/providers/cache.ts`, then run `yarn generate`.
35
+
36
+ ```ts
37
+ import { defineCacheProviderRegistration } from '@open-mercato/cache/provider'
38
+
39
+ export const cacheProviders = [
40
+ defineCacheProviderRegistration({
41
+ id: 'open-mercato/infinispan',
42
+ load: () => import('@open-mercato/cache-provider-infinispan').then((module) => module.provider),
43
+ settings: () => ({
44
+ servers: [
45
+ { host: process.env.INFINISPAN_HOST_1!, port: 11222 },
46
+ { host: process.env.INFINISPAN_HOST_2!, port: 11222 },
47
+ ],
48
+ cacheName: 'open-mercato',
49
+ auth: {
50
+ username: process.env.INFINISPAN_USER!,
51
+ password: process.env.INFINISPAN_PASSWORD!,
52
+ mechanism: 'SCRAM-SHA-256',
53
+ },
54
+ tls: { enabled: true, caFiles: ['/etc/ssl/infinispan-ca.pem'], serverName: 'infinispan.internal' },
55
+ }),
56
+ }),
57
+ ]
58
+ ```
59
+
60
+ Select it with `CACHE_PROVIDER=open-mercato/infinispan` and a stable `CACHE_PROVIDER_NAMESPACE` per deployment (all instances of one deployment share it; use a new namespace for an incompatible layout change).
61
+
62
+ Verified TLS is required by default. To use the plaintext test profile, set `CACHE_PROVIDER_ALLOW_INSECURE_DEVELOPMENT=1` in a development or test process. This profile reports `local` placement.
63
+
64
+ ## Settings
65
+
66
+ The schema is strict (unknown keys are rejected) and exported as `infinispanSettingsSchema`.
67
+
68
+ | Setting | Default | Notes |
69
+ |---|---|---|
70
+ | `servers` | required | 1–32 `{ host, port }` (port default `11222`). The client fails over between them. |
71
+ | `cacheName` | required | Dedicated cache (letters, digits, `.`, `_`, `-`). |
72
+ | `auth.username`, `auth.password` | required | Never logged; `redact()` hides them. |
73
+ | `auth.mechanism` | `SCRAM-SHA-256` | `SCRAM-SHA-256`, `SCRAM-SHA-384`, `SCRAM-SHA-512`, `DIGEST-MD5`. `PLAIN` is not accepted. |
74
+ | `tls` | required | `{ enabled: true, caFiles: [absolute PEM paths], serverName? }`. Server certificates are verified against `caFiles`; `serverName` sets SNI and the name checked against the certificate. |
75
+ | `protocolVersion` | `4.1` | `4.1`, `4.0`, `3.1`. Protocol auto-negotiation is deliberately unavailable (it crashes the client). |
76
+ | `topologyUpdates` | `true` | Set `false` when the addresses the servers advertise are not reachable from the app (Docker port mapping, NAT). Requests then go to the configured servers and the cluster forwards them. |
77
+ | `connectTimeoutMs` | `5000` | Bound on connecting and authenticating. |
78
+ | `commandTimeoutMs` | `5000` | Bound on every Hot Rod command. A timed-out connection is discarded and re-established on the next call. |
79
+ | `iteratorBatchSize` | `256` | Entries per iterator page for `keys`/`stats`/`clear`/`cleanup`, and keys per bulk read. |
80
+ | `concurrency` | `16` | Parallel commands per provider call. |
81
+ | `maxCasAttempts` | `64` | Versioned retry budget for one tag-index update or conditional remove. |
82
+ | `tagIndexShards` | `64` | Tag-index shards per tag. Part of the layout: change it only together with a new namespace. |
83
+ | `maxTagsPerEntry` | `64` | Entries above this (or above `maxValueBytes`) are not stored; the previous copy is removed and a warning is logged. |
84
+ | `maxValueBytes` | `4 MiB` | Encoded payload limit per entry. |
85
+ | `indexPruneGraceMs` | `120000` | Window after which a tag-index member whose entry is gone or rewritten may be pruned. Must be at least `6 × commandTimeoutMs`. A `set` refuses to write its entry later than `indexPruneGraceMs − 4 × commandTimeoutMs` after its index update, so clock skew between app hosts must stay below `3 × commandTimeoutMs` (see [Limitations](#limitations)). |
86
+
87
+ Errors use the shared `CacheProviderError` contract: `timeout` (connect or command bound exceeded), `unavailable` (transport, authentication, TLS, contention beyond `maxCasAttempts`), `load_failed` (unsupported client version), `invalid_settings` (field paths only). Messages never contain hosts, credentials or certificate paths.
88
+
89
+ ## Supported matrix
90
+
91
+ Only profiles with passing real-engine evidence are listed.
92
+
93
+ | Profile | Status |
94
+ |---|---|
95
+ | Infinispan Server `15.2.6.Final`, distributed cache, 2 clustered nodes, SCRAM-SHA-256 over TLS, `topologyUpdates: false` | Supported (conformance, engine suite, failover of one node) |
96
+ | Infinispan Server `15.2.6.Final`, single node, DIGEST-MD5 over plaintext Hot Rod | Development and test opt-in (conformance, engine suite) |
97
+ | DIGEST-MD5 over TLS | Supported (engine suite check) |
98
+
99
+ Not verified (do not advertise): `topologyUpdates: true` with client-side routing to advertised addresses (could not be exercised behind Docker port mapping); SCRAM-SHA-384/512 (accepted by the schema, same SASL code path, not run); clusters larger than two nodes; cross-site replication; Infinispan versions other than 15.2.6; protocol versions `4.0`/`3.1` beyond decoder unit tests; client certificate (mutual TLS) authentication (not offered by the schema).
100
+
101
+ ## Storage layout
102
+
103
+ All keys live in the dedicated cache under the deployment prefix `{namespace}:v2:`; enumeration, `clear` and `cleanup` only touch keys with that prefix.
104
+
105
+ - **Entry** `{ns}:v2:k:{physicalKey}` → JSON `{ f, w, t, x, e, d }`: format, unique write id, tags, logical expiry, encoding and the codec payload (base64 when compressed). TTLs are native per-entry Hot Rod lifespans, so expired entries disappear on the server.
106
+ - **Tag index shard** `{ns}:v2:t:{shards}:{i}:{tag}` → JSON map `physicalKey → [writeId, writtenAt, expiresAt]`. The shard is `sha1(physicalKey) mod tagIndexShards`. A shard's lifespan follows its longest-lived member (plus the grace window) and it has none while any member is immortal.
107
+ - **Tenant scope tag (not indexed).** The host wrapper adds `tenant:<id>:tag:__scope__` to every record of a tenant, and every such record's physical key starts with `tenant:<id>:key:`. Indexing that tag would make every write rewrite a shard whose size grows with the tenant. Layout v2 therefore never indexes the scope tag for keys under its tenant prefix: the entry key itself is the membership. A scope-tag record whose key is outside that prefix (not produced by the host) is still indexed normally.
108
+
109
+ Writes and invalidation:
110
+
111
+ 1. `set` adds `key → writeId` to every indexed tag's shard **before** writing the entry, with `getWithMetadata` + `replaceWithVersion` retry loops (`putIfAbsent` creates a shard). An entry is therefore never visible under an indexed tag that does not index it. The entry is written only inside the grace window after the index update. Index work per `set` depends on the number of ordinary tags, not on how many entries the tenant holds.
112
+ 2. `deleteByTags` reads the shards with bulk `getAll`, re-reads each candidate entry with `getWithMetadata`, and removes it with `removeWithVersion` only if its **current** tags still match. A concurrently retagged entry is left alone. Each removed record is counted once. For a tenant scope tag (tenant `clear()`), it additionally pages through the cache with the Hot Rod iterator, takes every entry key under `{ns}:v2:k:tenant:<id>:key:`, and applies the same re-read + `removeWithVersion` check. Every entry that existed before the call is returned by the iterator (Infinispan iterates segment by segment and returns every entry not modified during the iteration), so no membership can be lost through index races. An entry written concurrently with the clear may survive or be removed, as with any concurrent write.
113
+ 3. A member is pruned only with a versioned replace that re-checks its write id: immediately when this call removed exactly that write, and otherwise only after `indexPruneGraceMs` if the entry is gone or was rewritten. A pending write is never unindexed. `set` also drops members whose own TTL passed the grace window, and `cleanup()` garbage-collects index shards.
114
+ 4. Corrupt or undecodable entries are misses and are removed with a versioned delete.
115
+
116
+ ## Protocol choice (spike, 2026-11-24)
117
+
118
+ The spike ran against `quay.io/infinispan/server:15.2.6.Final` (arm64) with `infinispan@0.16.3`:
119
+
120
+ - Hot Rod `getWithMetadata`, `putIfAbsent`, `replaceWithVersion` and `removeWithVersion` are atomic: a 20-way concurrent increment via versioned replace ended at exactly 20, with 190 retries on one node and 162 retries across clients on different cluster members. Stale versions are refused for both replace and remove.
121
+ - `iterator(batchSize)` enumerates in bounded pages (1 001 entries in batches of 100), skips expired entries and works across both cluster members.
122
+ - Per-entry `lifespan` works at millisecond granularity (a 300 ms entry is gone after 450 ms).
123
+ - **REST v2 was rejected:** `PUT`/`DELETE` with a stale `If-Match` ETag still return `204` and apply unconditionally, and `?action=keys` has a `limit` but no cursor or offset for resumable paging. `POST` only gives create-if-absent.
124
+
125
+ ## Migration
126
+
127
+ - **Layout `v1` → `v2` (this release).** Keys moved from `{ns}:v1:` to `{ns}:v2:` because the tenant scope tag is no longer indexed. The provider ignores `v1` keys: after upgrading, the cache starts empty for the deployment (a cold cache, no wrong results). `v1` entries and shards that had a lifespan expire on their own. Shards with immortal members do not, so remove the `{ns}:v1:` keys once (or recreate the dedicated cache) after all app instances run the new version. Do not run old and new versions against the same namespace at the same time. Their invalidations would not see each other's writes.
128
+
129
+ ## Client defects worked around
130
+
131
+ `infinispan@0.16.3` has defects that break this provider unless handled. The package pins the exact version and refuses to load (`load_failed`) if it cannot apply its fix.
132
+
133
+ 1. **`getWithMetadata` and iterator pages split across socket reads.** A truncated value decodes as `value: undefined` and desynchronizes the connection, so later commands hang. Locally this hits values from about 64 KiB; over TLS or real networks it hits much smaller ones. In a TLS repro with 60 KiB values and 16 concurrent readers, the unpatched client returned 0 of 640 reads correctly and the patched one returned all 640. A truncated lifespan timestamp throws a `TypeError` inside the socket data handler, which **crashes the Node process**. The iterator page decoder shares the timestamp decoding and crashed the same way on a 5 000-entry tenant `clear()` of entries with a TTL. The provider wraps both decoders at load (`src/hotrodPatch.ts`) so a truncated frame waits for more bytes, as the transport already supports. Only out-of-bounds reads count as a truncated frame. Any other decoder error is rethrown. If the installed client does not expose the decoders in the expected shape, the provider fails with `load_failed` instead of running unpatched. The iterator also runs without per-entry metadata, which the provider never needed. Unit tests reproduce both upstream failures, and any versioned read that still arrives incomplete is a transport error, never a corrupt entry.
134
+ 2. **Protocol auto-negotiation (`version: 'auto'`) throws inside the socket handler** and crashes the process, so the settings only accept explicit versions.
135
+ 3. **No connect or command timeouts.** After a server restart the old connection hangs forever. The provider bounds every call and replaces the connection after a timeout or transport error.
136
+
137
+ These should be reported upstream. Re-qualify before changing the pinned client version.
138
+
139
+ ## Limitations
140
+
141
+ - **No eviction on the dedicated cache.** If the server evicts a tag-index shard, entries it indexed survive an invalidation of that tag until their TTL. Bound memory with TTLs (`CACHE_TTL` / per-entry `ttl`) and server sizing, not `max-count`/`max-size`.
142
+ - `keys`, `stats`, `clear`, `cleanup` and a tenant `clear()` (scope-tag `deleteByTags`) page through the whole dedicated cache with the Hot Rod iterator and filter by prefix client-side. The JS client cannot run server-side key filters. Their cost grows with the cache, not only the namespace or tenant. Keep one cache per Open Mercato deployment.
143
+ - An ordinary tag that a very large share of a tenant carries still grows its shards with its member count. Raise `tagIndexShards` (with a new namespace) if one tag spans tens of thousands of live entries.
144
+ - `returnExpired` is not supported: entries expire natively on the server.
145
+ - Index pruning uses wall-clock timestamps from the app hosts. A member is pruned only when its `writtenAt + indexPruneGraceMs` lies in the pruner's past, and a writer stops writing its entry `4 × commandTimeoutMs` before that point. The margin covers the entry `put` (up to one `commandTimeoutMs`) plus clock skew, so app-host clocks must agree within `3 × commandTimeoutMs` (use NTP).
146
+ - A command that times out may still be applied by the server later. Callers see a `timeout` error, and the cache remains consistent because every index change is versioned.
147
+
148
+ ## Evidence
149
+
150
+ These are **manual runs** on a developer machine, not CI. No CI job runs the container suites yet (see `packages/cache-redis-protocol/README.md` → *Proposed CI job*). All runs were on 2026-11-24 on a macOS arm64 Docker host with Node 26.12, `infinispan@0.16.3` and image `quay.io/infinispan/server:15.2.6.Final` (arm64) with `JAVA_OPTIONS=-Xmx512m`. Container suites are gated by `OM_CACHE_PROVIDER_CONTAINER_TESTS=1` and stop their containers in `afterAll`.
151
+
152
+ Command: `yarn workspace @open-mercato/cache-provider-infinispan test:containers` (or `yarn test:cache-providers:containers` from the repo root for every provider). Result: 3 suites, 45/45 passed, 54.4 s, layout `v2`.
153
+
154
+ | Suite | Topology / auth / transport | Result |
155
+ |---|---|---|
156
+ | `cluster-tls.container.test.ts` | 2-node distributed cache (`owners: 1`, real `cluster_members = 2`), SCRAM-SHA-256 + DIGEST-MD5 over TLS (throwaway CA, PKCS#12 server identity) | 21/21 passed: v1 conformance (16, incl. independent process and corrupt value), namespace fencing + native lifespan, untrusted CA and wrong password refused without leaking secrets, two-process retag race (30 rounds) and chaos run (2 writer processes + 1 invalidator, **0 missing index memberships**), failover after stopping one member |
157
+ | `single-node.container.test.ts` | 1 node, DIGEST-MD5 over plaintext Hot Rod | 21/21 passed: v1 conformance (16), native TTL, 300 KiB round-trip through versioned reads + 1 MiB oversize skip, scope-tag load test (below), frozen server (`docker pause`) → `timeout` within bound → reconnect, server restart → reconnect without app restart |
158
+ | `packed.container.test.ts` | 1 node, SCRAM-SHA-256 | 3/3 passed: `yarn pack` tarball installed into a fresh app (no sibling adapters, no tests in the tarball), consumer `tsc` type-check of a registration, `resolveCacheProvider` + `createCacheService` workflow against the server |
159
+ | Unit (`yarn test`, no Docker) | in-memory versioned fake | 41 passed: settings/redaction, layout, decoder guards (reproduce both upstream defects, rethrow real decode errors, refuse an unexpected client shape), strategy logic incl. scope-tag prefix invalidation, conformance kit over the fake (logic only, not engine evidence) |
160
+
161
+ ### Scope-tag load test (`single-node.container.test.ts`)
162
+
163
+ 4 services with separate connections, 10 concurrent writers each (40 concurrent `set` calls). They write 5 000 entries into one tenant through the tenant wrapper, which means 10 000 physical records carrying the scope tag plus one of 10 ordinary tags, ~1 KiB each, 10 min TTL. Then 2 writers keep writing into the tenant while a third client runs the tenant `clear()`.
164
+
165
+ | Measure | Result |
166
+ |---|---|
167
+ | `set` p50 / p95, first 500 entries | 12.8 / 16.3 ms |
168
+ | `set` p50 / p95, last 500 entries (tenant at ~5 000) | 11.7 / 13.2 ms |
169
+ | Fill of 5 000 entries | 1.48 s |
170
+ | Scope-tag index shards in the cache | **0** (642 shards for the 10 ordinary tags) |
171
+ | Tenant `clear()` with 2 concurrent writers | 1.03 s. All 5 000 pre-existing entries removed, 390 concurrent writes during the clear, other tenant untouched |
172
+
173
+ Write latency is flat in tenant size. With layout `v1` the same scope tag sat in every write and its shards grew with the tenant.
174
+
175
+ ### Performance qualification (`qualify.container.test.ts`)
176
+
177
+ Command: `OM_QUALIFY_OUT=/tmp/qualify.json OM_QUALIFY_SHARDS=64 OM_QUALIFY_CARDINALITY=1000,5000,20000 yarn workspace @open-mercato/cache-provider-infinispan qualify` (manual run, 2026-11-24, layout `v2`).
178
+
179
+ 2-node TLS cluster above, `topologyUpdates: false`, `tagIndexShards: 64`, 2 clients with separate connections running concurrently, 600 ops each (60% get / 30% set of a ~1 KiB JSON value with 2 of 20 tags / 10% `deleteByTags`) over 300 keys in one tenant. Latency is wall-clock per service call including the tenant wrapper (this historical run used the two-record host layout). Commands are Hot Rod commands per call.
180
+
181
+ | Operation | p50 | p95 | Hot Rod commands per call |
182
+ |---|---|---|---|
183
+ | `get` | 0.48 ms | 1.05 ms | 1.0 |
184
+ | `set` (2 tags + tenant scope tag) | 4.58 ms | 7.06 ms | 10.0 (v1: 14.0) |
185
+ | `deleteByTags` | 1.34 ms | 1.93 ms | 2.8 |
186
+
187
+ Throughput of the mixed run was 1 042 ops/s across both clients (sequential per client). Per-tenant cardinality (50-way concurrent fill with one ordinary tag, 100 probe `set` calls into the populated tenant, then `clear`):
188
+
189
+ | Entries in tenant | `set` p50 / p95 | `clear` |
190
+ |---|---|---|
191
+ | 1 000 | 2.47 / 4.99 ms | 367 ms |
192
+ | 5 000 | 2.25 / 3.80 ms | 1.30 s |
193
+ | 20 000 | 3.72 / 5.49 ms | 3.99 s |
194
+
195
+ With layout `v1`, 20 000 entries per tenant (even with 256 shards) and 5 000 with 16 shards hit the 10 s command timeout during the fill. With `v2` all three sizes pass with the default 64 shards. `clear` grows linearly because it pages through the cache. Stock Redis was not measured side by side in this package. Compare with the Redis provider's evidence.
196
+
197
+
198
+ ## Development
199
+
200
+ ```bash
201
+ yarn workspace @open-mercato/cache-provider-infinispan test # unit tests, no Docker
202
+ yarn workspace @open-mercato/cache-provider-infinispan test:containers # real Infinispan via Testcontainers
203
+ OM_QUALIFY_OUT=/tmp/qualify.json OM_QUALIFY_SHARDS=64 OM_QUALIFY_CARDINALITY=1000,5000 \
204
+ yarn workspace @open-mercato/cache-provider-infinispan qualify # perf qualification (2-node TLS cluster)
205
+ ```
206
+
207
+ The container suites need Docker (about 0.3 GB RSS per Infinispan node with `-Xmx512m`). They generate a throwaway CA and server certificate with `openssl` and stop their containers afterwards.
package/dist/client.js ADDED
@@ -0,0 +1,166 @@
1
+ import { CacheProviderError } from "@open-mercato/cache/provider";
2
+ import { applyHotRodDecodePatch } from "./hotrodPatch.js";
3
+ const PROVIDER_ID = "open-mercato/infinispan";
4
+ function isHotRodModule(value) {
5
+ return typeof value === "object" && value !== null && typeof value.client === "function";
6
+ }
7
+ async function loadHotRodConnector() {
8
+ if (!await applyHotRodDecodePatch().catch(() => false)) {
9
+ throw new CacheProviderError("load_failed", `Cache provider "${PROVIDER_ID}" does not support the installed infinispan client version`, { providerId: PROVIDER_ID });
10
+ }
11
+ const imported = await import("infinispan");
12
+ const candidates = [imported, imported.default];
13
+ const hotRod = candidates.find(isHotRodModule);
14
+ if (!hotRod) {
15
+ throw new CacheProviderError("load_failed", `Cache provider "${PROVIDER_ID}" could not load the infinispan Hot Rod client`, { providerId: PROVIDER_ID });
16
+ }
17
+ return (servers, options) => hotRod.client(servers, options);
18
+ }
19
+ function buildHotRodClientOptions(config) {
20
+ return {
21
+ version: config.protocolVersion,
22
+ cacheName: config.cacheName,
23
+ topologyUpdates: config.topologyUpdates,
24
+ maxRetries: Math.max(1, config.servers.length),
25
+ authentication: {
26
+ enabled: true,
27
+ saslMechanism: config.auth.mechanism,
28
+ userName: config.auth.username,
29
+ password: config.auth.password
30
+ },
31
+ ...config.tls ? {
32
+ ssl: {
33
+ enabled: true,
34
+ trustCerts: [...config.tls.caFiles],
35
+ ...config.tls.serverName ? { sniHostName: config.tls.serverName } : {}
36
+ }
37
+ } : {},
38
+ dataFormat: { keyType: "text/plain", valueType: "text/plain" }
39
+ };
40
+ }
41
+ const TIMEOUT_MARKER = /* @__PURE__ */ Symbol("hotrod-timeout");
42
+ function unavailable(operation, cause) {
43
+ return new CacheProviderError("unavailable", `Cache provider "${PROVIDER_ID}" ${operation} failed`, { providerId: PROVIDER_ID, cause });
44
+ }
45
+ function timedOut(operation, ms) {
46
+ return new CacheProviderError("timeout", `Cache provider "${PROVIDER_ID}" ${operation} did not complete within ${ms}ms`, { providerId: PROVIDER_ID });
47
+ }
48
+ async function withTimeout(promise, ms) {
49
+ let timer = null;
50
+ const timeout = new Promise((resolve) => {
51
+ timer = setTimeout(() => resolve(TIMEOUT_MARKER), ms);
52
+ });
53
+ try {
54
+ return await Promise.race([promise, timeout]);
55
+ } finally {
56
+ if (timer) clearTimeout(timer);
57
+ }
58
+ }
59
+ function disconnectQuietly(client, ms) {
60
+ void withTimeout(client.disconnect().catch(() => void 0), ms).catch(() => void 0);
61
+ }
62
+ function createHotRodGateway(options) {
63
+ const { connector, config } = options;
64
+ const clientOptions = buildHotRodClientOptions(config);
65
+ const servers = config.servers.map((server) => ({ host: server.host, port: server.port }));
66
+ let current = null;
67
+ let connecting = null;
68
+ let closed = false;
69
+ const discard = (client) => {
70
+ if (current === client) current = null;
71
+ disconnectQuietly(client, config.commandTimeoutMs);
72
+ };
73
+ const acquire = async () => {
74
+ if (closed) throw new CacheProviderError("unavailable", `Cache provider "${PROVIDER_ID}" is closed`, { providerId: PROVIDER_ID });
75
+ if (current) return current;
76
+ if (!connecting) {
77
+ const attempt = connector(servers, clientOptions);
78
+ const guarded = withTimeout(attempt, config.connectTimeoutMs).then(
79
+ (result) => {
80
+ if (result === TIMEOUT_MARKER) {
81
+ void attempt.then((late) => disconnectQuietly(late, config.commandTimeoutMs), () => void 0);
82
+ throw timedOut("connect", config.connectTimeoutMs);
83
+ }
84
+ if (closed) {
85
+ disconnectQuietly(result, config.commandTimeoutMs);
86
+ throw new CacheProviderError("unavailable", `Cache provider "${PROVIDER_ID}" is closed`, { providerId: PROVIDER_ID });
87
+ }
88
+ current = result;
89
+ return result;
90
+ },
91
+ (error) => {
92
+ throw error instanceof CacheProviderError ? error : unavailable("connect", error);
93
+ }
94
+ );
95
+ connecting = guarded;
96
+ guarded.then(
97
+ () => {
98
+ if (connecting === guarded) connecting = null;
99
+ },
100
+ () => {
101
+ if (connecting === guarded) connecting = null;
102
+ }
103
+ );
104
+ }
105
+ return connecting;
106
+ };
107
+ const run = async (operation, body) => {
108
+ const client = await acquire();
109
+ let result;
110
+ try {
111
+ result = await withTimeout(body(client), config.commandTimeoutMs);
112
+ } catch (error) {
113
+ discard(client);
114
+ throw error instanceof CacheProviderError ? error : unavailable(operation, error);
115
+ }
116
+ if (result === TIMEOUT_MARKER) {
117
+ discard(client);
118
+ throw timedOut(operation, config.commandTimeoutMs);
119
+ }
120
+ return result;
121
+ };
122
+ const getVersioned = (operation, key) => run(operation, async (client) => {
123
+ const stored = await client.getWithMetadata(key);
124
+ if (stored === void 0) return void 0;
125
+ if (typeof stored.value !== "string" || !Buffer.isBuffer(stored.version)) {
126
+ throw new CacheProviderError("unavailable", `Cache provider "${PROVIDER_ID}" ${operation} returned an incomplete versioned read`, { providerId: PROVIDER_ID });
127
+ }
128
+ return { value: stored.value, version: stored.version };
129
+ });
130
+ const scan = async (visit) => {
131
+ const iterator = await run("iterator open", (client) => client.iterator(config.iteratorBatchSize));
132
+ try {
133
+ for (; ; ) {
134
+ const step = await run("iterator next", () => iterator.next());
135
+ if (step.done) break;
136
+ if (typeof step.key === "string") await visit(step.key, step.value);
137
+ }
138
+ } finally {
139
+ await withTimeout(iterator.close().catch(() => void 0), config.commandTimeoutMs).catch(() => void 0);
140
+ }
141
+ };
142
+ return {
143
+ run,
144
+ getVersioned,
145
+ scan,
146
+ async connect() {
147
+ await acquire();
148
+ },
149
+ async close() {
150
+ closed = true;
151
+ const client = current;
152
+ current = null;
153
+ const pending = connecting;
154
+ connecting = null;
155
+ if (pending) await pending.catch(() => void 0);
156
+ if (client) await withTimeout(client.disconnect().catch(() => void 0), config.commandTimeoutMs).catch(() => void 0);
157
+ }
158
+ };
159
+ }
160
+ export {
161
+ PROVIDER_ID,
162
+ buildHotRodClientOptions,
163
+ createHotRodGateway,
164
+ loadHotRodConnector
165
+ };
166
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/client.ts"],
4
+ "sourcesContent": ["import { CacheProviderError } from '@open-mercato/cache/provider'\nimport { applyHotRodDecodePatch } from './hotrodPatch'\nimport type { InfinispanSettings } from './settings'\n\nexport const PROVIDER_ID = 'open-mercato/infinispan'\n\nexport type HotRodMetadataValue = {\n value: string\n version: Buffer\n}\n\nexport type HotRodStoreOptions = {\n lifespan?: string\n}\n\nexport type HotRodIteratorStep = {\n done: boolean\n key?: unknown\n value?: unknown\n version?: unknown\n}\n\nexport type HotRodIterator = {\n next(): Promise<HotRodIteratorStep>\n close(): Promise<unknown>\n}\n\nexport type HotRodClient = {\n get(key: string): Promise<string | undefined>\n getWithMetadata(key: string): Promise<HotRodMetadataValue | undefined>\n getAll(keys: string[]): Promise<Array<{ key: string; value: string }>>\n containsKey(key: string): Promise<boolean>\n put(key: string, value: string, options?: HotRodStoreOptions): Promise<unknown>\n putIfAbsent(key: string, value: string, options?: HotRodStoreOptions): Promise<boolean>\n replaceWithVersion(key: string, value: string, version: Buffer, options?: HotRodStoreOptions): Promise<boolean>\n remove(key: string): Promise<boolean>\n removeWithVersion(key: string, version: Buffer): Promise<boolean>\n iterator(batchSize: number, options?: { metadata?: boolean }): Promise<HotRodIterator>\n disconnect(): Promise<void>\n}\n\nexport type HotRodServerAddress = { host: string; port: number }\n\nexport type HotRodClientOptions = {\n version: string\n cacheName: string\n topologyUpdates: boolean\n maxRetries: number\n authentication: {\n enabled: true\n saslMechanism: string\n userName: string\n password: string\n }\n ssl?: {\n enabled: true\n trustCerts: string[]\n sniHostName?: string\n }\n dataFormat: { keyType: 'text/plain'; valueType: 'text/plain' }\n}\n\nexport type HotRodConnector = (servers: HotRodServerAddress[], options: HotRodClientOptions) => Promise<HotRodClient>\n\ntype HotRodModule = { client: HotRodConnector }\n\nfunction isHotRodModule(value: unknown): value is HotRodModule {\n return typeof value === 'object' && value !== null && typeof (value as { client?: unknown }).client === 'function'\n}\n\nexport async function loadHotRodConnector(): Promise<HotRodConnector> {\n if (!await applyHotRodDecodePatch().catch(() => false)) {\n throw new CacheProviderError('load_failed', `Cache provider \"${PROVIDER_ID}\" does not support the installed infinispan client version`, { providerId: PROVIDER_ID })\n }\n const imported: unknown = await import('infinispan')\n const candidates = [imported, (imported as { default?: unknown }).default]\n const hotRod = candidates.find(isHotRodModule)\n if (!hotRod) {\n throw new CacheProviderError('load_failed', `Cache provider \"${PROVIDER_ID}\" could not load the infinispan Hot Rod client`, { providerId: PROVIDER_ID })\n }\n return (servers, options) => hotRod.client(servers, options)\n}\n\nexport function buildHotRodClientOptions(config: InfinispanSettings): HotRodClientOptions {\n return {\n version: config.protocolVersion,\n cacheName: config.cacheName,\n topologyUpdates: config.topologyUpdates,\n maxRetries: Math.max(1, config.servers.length),\n authentication: {\n enabled: true,\n saslMechanism: config.auth.mechanism,\n userName: config.auth.username,\n password: config.auth.password,\n },\n ...(config.tls\n ? {\n ssl: {\n enabled: true as const,\n trustCerts: [...config.tls.caFiles],\n ...(config.tls.serverName ? { sniHostName: config.tls.serverName } : {}),\n },\n }\n : {}),\n dataFormat: { keyType: 'text/plain', valueType: 'text/plain' },\n }\n}\n\nexport type HotRodGateway = {\n run<T>(operation: string, body: (client: HotRodClient) => Promise<T>): Promise<T>\n getVersioned(operation: string, key: string): Promise<HotRodMetadataValue | undefined>\n scan(visit: (key: string, value: unknown) => Promise<void> | void): Promise<void>\n connect(): Promise<void>\n close(): Promise<void>\n}\n\nexport type HotRodGatewayOptions = {\n connector: HotRodConnector\n config: InfinispanSettings\n}\n\nconst TIMEOUT_MARKER = Symbol('hotrod-timeout')\n\nfunction unavailable(operation: string, cause?: unknown): CacheProviderError {\n return new CacheProviderError('unavailable', `Cache provider \"${PROVIDER_ID}\" ${operation} failed`, { providerId: PROVIDER_ID, cause })\n}\n\nfunction timedOut(operation: string, ms: number): CacheProviderError {\n return new CacheProviderError('timeout', `Cache provider \"${PROVIDER_ID}\" ${operation} did not complete within ${ms}ms`, { providerId: PROVIDER_ID })\n}\n\nasync function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | typeof TIMEOUT_MARKER> {\n let timer: ReturnType<typeof setTimeout> | null = null\n const timeout = new Promise<typeof TIMEOUT_MARKER>((resolve) => {\n timer = setTimeout(() => resolve(TIMEOUT_MARKER), ms)\n })\n try {\n return await Promise.race([promise, timeout])\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\nfunction disconnectQuietly(client: HotRodClient, ms: number): void {\n void withTimeout(client.disconnect().catch(() => undefined), ms).catch(() => undefined)\n}\n\nexport function createHotRodGateway(options: HotRodGatewayOptions): HotRodGateway {\n const { connector, config } = options\n const clientOptions = buildHotRodClientOptions(config)\n const servers = config.servers.map((server) => ({ host: server.host, port: server.port }))\n let current: HotRodClient | null = null\n let connecting: Promise<HotRodClient> | null = null\n let closed = false\n\n const discard = (client: HotRodClient) => {\n if (current === client) current = null\n disconnectQuietly(client, config.commandTimeoutMs)\n }\n\n const acquire = async (): Promise<HotRodClient> => {\n if (closed) throw new CacheProviderError('unavailable', `Cache provider \"${PROVIDER_ID}\" is closed`, { providerId: PROVIDER_ID })\n if (current) return current\n if (!connecting) {\n const attempt = connector(servers, clientOptions)\n const guarded = withTimeout(attempt, config.connectTimeoutMs).then(\n (result) => {\n if (result === TIMEOUT_MARKER) {\n void attempt.then((late) => disconnectQuietly(late, config.commandTimeoutMs), () => undefined)\n throw timedOut('connect', config.connectTimeoutMs)\n }\n if (closed) {\n disconnectQuietly(result, config.commandTimeoutMs)\n throw new CacheProviderError('unavailable', `Cache provider \"${PROVIDER_ID}\" is closed`, { providerId: PROVIDER_ID })\n }\n current = result\n return result\n },\n (error: unknown) => {\n throw error instanceof CacheProviderError ? error : unavailable('connect', error)\n },\n )\n connecting = guarded\n guarded.then(\n () => { if (connecting === guarded) connecting = null },\n () => { if (connecting === guarded) connecting = null },\n )\n }\n return connecting\n }\n\n const run = async <T>(operation: string, body: (client: HotRodClient) => Promise<T>): Promise<T> => {\n const client = await acquire()\n let result: T | typeof TIMEOUT_MARKER\n try {\n result = await withTimeout(body(client), config.commandTimeoutMs)\n } catch (error) {\n discard(client)\n throw error instanceof CacheProviderError ? error : unavailable(operation, error)\n }\n if (result === TIMEOUT_MARKER) {\n discard(client)\n throw timedOut(operation, config.commandTimeoutMs)\n }\n return result\n }\n\n const getVersioned = (operation: string, key: string) => run(operation, async (client) => {\n const stored = await client.getWithMetadata(key)\n if (stored === undefined) return undefined\n if (typeof stored.value !== 'string' || !Buffer.isBuffer(stored.version)) {\n throw new CacheProviderError('unavailable', `Cache provider \"${PROVIDER_ID}\" ${operation} returned an incomplete versioned read`, { providerId: PROVIDER_ID })\n }\n return { value: stored.value, version: stored.version }\n })\n\n const scan = async (visit: (key: string, value: unknown) => Promise<void> | void): Promise<void> => {\n const iterator = await run('iterator open', (client) => client.iterator(config.iteratorBatchSize))\n try {\n for (;;) {\n const step = await run('iterator next', () => iterator.next())\n if (step.done) break\n if (typeof step.key === 'string') await visit(step.key, step.value)\n }\n } finally {\n await withTimeout(iterator.close().catch(() => undefined), config.commandTimeoutMs).catch(() => undefined)\n }\n }\n\n return {\n run,\n getVersioned,\n scan,\n async connect() {\n await acquire()\n },\n async close() {\n closed = true\n const client = current\n current = null\n const pending = connecting\n connecting = null\n if (pending) await pending.catch(() => undefined)\n if (client) await withTimeout(client.disconnect().catch(() => undefined), config.commandTimeoutMs).catch(() => undefined)\n },\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGhC,MAAM,cAAc;AA8D3B,SAAS,eAAe,OAAuC;AAC7D,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAA+B,WAAW;AAC1G;AAEA,eAAsB,sBAAgD;AACpE,MAAI,CAAC,MAAM,uBAAuB,EAAE,MAAM,MAAM,KAAK,GAAG;AACtD,UAAM,IAAI,mBAAmB,eAAe,mBAAmB,WAAW,8DAA8D,EAAE,YAAY,YAAY,CAAC;AAAA,EACrK;AACA,QAAM,WAAoB,MAAM,OAAO,YAAY;AACnD,QAAM,aAAa,CAAC,UAAW,SAAmC,OAAO;AACzE,QAAM,SAAS,WAAW,KAAK,cAAc;AAC7C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,mBAAmB,eAAe,mBAAmB,WAAW,kDAAkD,EAAE,YAAY,YAAY,CAAC;AAAA,EACzJ;AACA,SAAO,CAAC,SAAS,YAAY,OAAO,OAAO,SAAS,OAAO;AAC7D;AAEO,SAAS,yBAAyB,QAAiD;AACxF,SAAO;AAAA,IACL,SAAS,OAAO;AAAA,IAChB,WAA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,MAAM,MAAM,MAAS;AAAA,IAC3G;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,MAAM,UAAU;AACd,YAAM,QAAQ;AAAA,IAChB;AAAA,IACA,MAAM,QAAQ;AACZ,eAAS;AACT,YAAM,SAAS;AACf,gBAAU;AACV,YAAM,UAAU;AAChB,mBAAa;AACb,UAAI,QAAS,OAAM,QAAQ,MAAM,MAAM,MAAS;AAChD,UAAI,OAAQ,OAAM,YAAY,OAAO,WAAW,EAAE,MAAM,MAAM,MAAS,GAAG,OAAO,gBAAgB,EAAE,MAAM,MAAM,MAAS;AAAA,IAC1H;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,82 @@
1
+ const PINNED_PROTOCOL_VERSIONS = ["4.1", "4.0", "3.1"];
2
+ const PROBE_OPTIONS = { dataFormat: { keyType: "text/plain", valueType: "text/plain" } };
3
+ const PATCH_MARKER = /* @__PURE__ */ Symbol.for("@open-mercato/cache-provider-infinispan/split-frame-decoders");
4
+ function isProtocolsModule(value) {
5
+ return typeof value === "object" && value !== null && typeof value.resolve === "function";
6
+ }
7
+ function exposesPatchedDecoders(protocols) {
8
+ return PINNED_PROTOCOL_VERSIONS.every((version) => {
9
+ try {
10
+ const protocol = protocols.resolve(version, PROBE_OPTIONS);
11
+ if (typeof protocol !== "object" || protocol === null) return false;
12
+ const candidate = protocol;
13
+ return typeof candidate.decodeWithMeta === "function" && typeof candidate.decodeNextEntries === "function";
14
+ } catch {
15
+ return false;
16
+ }
17
+ });
18
+ }
19
+ function isTruncatedVersionedValue(decoded) {
20
+ if (!decoded.continue) return false;
21
+ const result = decoded.result;
22
+ if (typeof result !== "object" || result === null) return false;
23
+ return "version" in result && result.value === void 0;
24
+ }
25
+ function isIncompleteFrameError(error) {
26
+ if (typeof error !== "object" || error === null) return false;
27
+ const { name, code, message } = error;
28
+ if (name === "RangeError") return code === "ERR_OUT_OF_RANGE" || code === "ERR_BUFFER_OUT_OF_BOUNDS";
29
+ return name === "TypeError" && typeof message === "string" && /^Cannot read properties of undefined \(reading '(length|\d+)'\)$/.test(message);
30
+ }
31
+ function hasTruncatedIteratorEntry(decoded) {
32
+ if (!decoded.continue || !Array.isArray(decoded.result)) return false;
33
+ return decoded.result.some((entry) => typeof entry !== "object" || entry === null || entry.key === void 0 || entry.value === void 0);
34
+ }
35
+ function guardDecoder(decoder, isTruncated) {
36
+ return (header, bytebuf) => {
37
+ let decoded;
38
+ try {
39
+ decoded = decoder(header, bytebuf);
40
+ } catch (error) {
41
+ if (isIncompleteFrameError(error)) return { continue: false };
42
+ throw error;
43
+ }
44
+ return isTruncated(decoded) ? { continue: false } : decoded;
45
+ };
46
+ }
47
+ function guardDecodeWithMeta(decoder) {
48
+ return guardDecoder(decoder, isTruncatedVersionedValue);
49
+ }
50
+ function guardDecodeNextEntries(decoder) {
51
+ return guardDecoder(decoder, hasTruncatedIteratorEntry);
52
+ }
53
+ function patchHotRodProtocols(candidate) {
54
+ const modules = [candidate?.default, candidate];
55
+ const protocols = modules.find(isProtocolsModule);
56
+ if (!protocols) return false;
57
+ const marked = protocols;
58
+ if (marked[PATCH_MARKER]) return true;
59
+ if (!exposesPatchedDecoders(protocols)) return false;
60
+ const resolve = protocols.resolve;
61
+ marked.resolve = (version, options) => {
62
+ const protocol = resolve(version, options);
63
+ const decodeWithMeta = protocol.decodeWithMeta;
64
+ const decodeNextEntries = protocol.decodeNextEntries;
65
+ protocol.decodeWithMeta = () => guardDecodeWithMeta(decodeWithMeta.call(protocol));
66
+ protocol.decodeNextEntries = () => guardDecodeNextEntries(decodeNextEntries.call(protocol));
67
+ return protocol;
68
+ };
69
+ marked[PATCH_MARKER] = true;
70
+ return true;
71
+ }
72
+ async function applyHotRodDecodePatch() {
73
+ return patchHotRodProtocols(await import("infinispan/lib/protocols.js"));
74
+ }
75
+ export {
76
+ applyHotRodDecodePatch,
77
+ guardDecodeNextEntries,
78
+ guardDecodeWithMeta,
79
+ isIncompleteFrameError,
80
+ patchHotRodProtocols
81
+ };
82
+ //# sourceMappingURL=hotrodPatch.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hotrodPatch.ts"],
4
+ "sourcesContent": ["/// <reference path=\"./infinispan-protocols.d.ts\" />\nexport type HotRodDecodeResult = { result?: unknown; continue: boolean }\nexport type HotRodDecoder = (header: unknown, bytebuf: unknown) => HotRodDecodeResult\n\ntype HotRodProtocol = { decodeWithMeta: () => HotRodDecoder; decodeNextEntries: () => HotRodDecoder }\n\nconst PINNED_PROTOCOL_VERSIONS = ['4.1', '4.0', '3.1'] as const\nconst PROBE_OPTIONS = { dataFormat: { keyType: 'text/plain', valueType: 'text/plain' } }\n\ntype HotRodProtocolsModule = {\n resolve: (version: string, options: unknown) => HotRodProtocol\n}\n\nconst PATCH_MARKER = Symbol.for('@open-mercato/cache-provider-infinispan/split-frame-decoders')\n\nfunction isProtocolsModule(value: unknown): value is HotRodProtocolsModule {\n return typeof value === 'object' && value !== null && typeof (value as { resolve?: unknown }).resolve === 'function'\n}\n\nfunction exposesPatchedDecoders(protocols: HotRodProtocolsModule): boolean {\n return PINNED_PROTOCOL_VERSIONS.every((version) => {\n try {\n const protocol: unknown = protocols.resolve(version, PROBE_OPTIONS)\n if (typeof protocol !== 'object' || protocol === null) return false\n const candidate = protocol as { decodeWithMeta?: unknown; decodeNextEntries?: unknown }\n return typeof candidate.decodeWithMeta === 'function' && typeof candidate.decodeNextEntries === 'function'\n } catch {\n return false\n }\n })\n}\n\nfunction isTruncatedVersionedValue(decoded: HotRodDecodeResult): boolean {\n if (!decoded.continue) return false\n const result = decoded.result\n if (typeof result !== 'object' || result === null) return false\n return 'version' in result && (result as { value?: unknown }).value === undefined\n}\n\nexport function isIncompleteFrameError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false\n const { name, code, message } = error as { name?: unknown; code?: unknown; message?: unknown }\n if (name === 'RangeError') return code === 'ERR_OUT_OF_RANGE' || code === 'ERR_BUFFER_OUT_OF_BOUNDS'\n return name === 'TypeError' && typeof message === 'string' && /^Cannot read properties of undefined \\(reading '(length|\\d+)'\\)$/.test(message)\n}\n\nfunction hasTruncatedIteratorEntry(decoded: HotRodDecodeResult): boolean {\n if (!decoded.continue || !Array.isArray(decoded.result)) return false\n return decoded.result.some((entry: unknown) =>\n typeof entry !== 'object' || entry === null\n || (entry as { key?: unknown }).key === undefined\n || (entry as { value?: unknown }).value === undefined)\n}\n\nfunction guardDecoder(decoder: HotRodDecoder, isTruncated: (decoded: HotRodDecodeResult) => boolean): HotRodDecoder {\n return (header, bytebuf) => {\n let decoded: HotRodDecodeResult\n try {\n decoded = decoder(header, bytebuf)\n } catch (error) {\n if (isIncompleteFrameError(error)) return { continue: false }\n throw error\n }\n return isTruncated(decoded) ? { continue: false } : decoded\n }\n}\n\nexport function guardDecodeWithMeta(decoder: HotRodDecoder): HotRodDecoder {\n return guardDecoder(decoder, isTruncatedVersionedValue)\n}\n\nexport function guardDecodeNextEntries(decoder: HotRodDecoder): HotRodDecoder {\n return guardDecoder(decoder, hasTruncatedIteratorEntry)\n}\n\n/**\n * infinispan@0.16.x `getWithMetadata` (and the iterator page decoder, which\n * shares the timestamp decoding) mis-handles a response split across socket\n * reads: a truncated value decodes as `value: undefined` (desynchronizing the\n * connection) and a truncated lifespan timestamp throws inside the socket data\n * handler (crashing the process). Make the decoder ask the transport for more\n * bytes instead, so it rewinds and retries; a frame that never completes is\n * bounded by the provider's command timeout and connection discard. Only\n * out-of-bounds reads count as an incomplete frame; any other decoder error is\n * rethrown. Returns false (the provider then fails with `load_failed`) when the\n * installed client does not expose the decoder shape this patch relies on.\n */\nexport function patchHotRodProtocols(candidate: unknown): boolean {\n const modules = [(candidate as { default?: unknown } | null)?.default, candidate]\n const protocols = modules.find(isProtocolsModule)\n if (!protocols) return false\n const marked = protocols as HotRodProtocolsModule & { [PATCH_MARKER]?: true }\n if (marked[PATCH_MARKER]) return true\n if (!exposesPatchedDecoders(protocols)) return false\n const resolve = protocols.resolve\n marked.resolve = (version, options) => {\n const protocol = resolve(version, options)\n const decodeWithMeta = protocol.decodeWithMeta\n const decodeNextEntries = protocol.decodeNextEntries\n protocol.decodeWithMeta = () => guardDecodeWithMeta(decodeWithMeta.call(protocol))\n protocol.decodeNextEntries = () => guardDecodeNextEntries(decodeNextEntries.call(protocol))\n return protocol\n }\n marked[PATCH_MARKER] = true\n return true\n}\n\nexport async function applyHotRodDecodePatch(): Promise<boolean> {\n return patchHotRodProtocols(await import('infinispan/lib/protocols.js'))\n}\n"],
5
+ "mappings": "AAMA,MAAM,2BAA2B,CAAC,OAAO,OAAO,KAAK;AACrD,MAAM,gBAAgB,EAAE,YAAY,EAAE,SAAS,cAAc,WAAW,aAAa,EAAE;AAMvF,MAAM,eAAe,uBAAO,IAAI,8DAA8D;AAE9F,SAAS,kBAAkB,OAAgD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAAgC,YAAY;AAC5G;AAEA,SAAS,uBAAuB,WAA2C;AACzE,SAAO,yBAAyB,MAAM,CAAC,YAAY;AACjD,QAAI;AACF,YAAM,WAAoB,UAAU,QAAQ,SAAS,aAAa;AAClE,UAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;AAC9D,YAAM,YAAY;AAClB,aAAO,OAAO,UAAU,mBAAmB,cAAc,OAAO,UAAU,sBAAsB;AAAA,IAClG,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;AAEA,SAAS,0BAA0B,SAAsC;AACvE,MAAI,CAAC,QAAQ,SAAU,QAAO;AAC9B,QAAM,SAAS,QAAQ;AACvB,MAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;AAC1D,SAAO,aAAa,UAAW,OAA+B,UAAU;AAC1E;AAEO,SAAS,uBAAuB,OAAyB;AAC9D,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,EAAE,MAAM,MAAM,QAAQ,IA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F,aAAS,oBAAoB,MAAM,uBAAuB,kBAAkB,KAAK,QAAQ,CAAC;AAC1F,WAAO;AAAA,EACT;AACA,SAAO,YAAY,IAAI;AACvB,SAAO;AACT;AAEA,eAAsB,yBAA2C;AAC/D,SAAO,qBAAqB,MAAM,OAAO,6BAA6B,CAAC;AACzE;",
6
+ "names": []
7
+ }
package/dist/index.js ADDED
@@ -0,0 +1,40 @@
1
+ import { provider, createInfinispanProvider } from "./provider.js";
2
+ import { default as default2 } from "./provider.js";
3
+ import {
4
+ infinispanSettingsSchema,
5
+ redactInfinispanSettings,
6
+ INFINISPAN_PROTOCOL_VERSIONS,
7
+ INFINISPAN_SASL_MECHANISMS
8
+ } from "./settings.js";
9
+ import {
10
+ PROVIDER_ID,
11
+ buildHotRodClientOptions
12
+ } from "./client.js";
13
+ import {
14
+ LAYOUT_VERSION,
15
+ entryKey,
16
+ entryKeyPrefix,
17
+ namespacePrefix,
18
+ tagKeyPrefix,
19
+ tagShardKey,
20
+ tagShardIndex
21
+ } from "./layout.js";
22
+ export {
23
+ INFINISPAN_PROTOCOL_VERSIONS,
24
+ INFINISPAN_SASL_MECHANISMS,
25
+ LAYOUT_VERSION,
26
+ PROVIDER_ID,
27
+ buildHotRodClientOptions,
28
+ createInfinispanProvider,
29
+ default2 as default,
30
+ entryKey,
31
+ entryKeyPrefix,
32
+ infinispanSettingsSchema,
33
+ namespacePrefix,
34
+ provider,
35
+ redactInfinispanSettings,
36
+ tagKeyPrefix,
37
+ tagShardIndex,
38
+ tagShardKey
39
+ };
40
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["export { provider, createInfinispanProvider, type CreateInfinispanProviderOptions } from './provider'\nexport { default } from './provider'\nexport {\n infinispanSettingsSchema,\n redactInfinispanSettings,\n INFINISPAN_PROTOCOL_VERSIONS,\n INFINISPAN_SASL_MECHANISMS,\n type InfinispanSettings,\n type InfinispanSettingsInput,\n} from './settings'\nexport {\n PROVIDER_ID,\n buildHotRodClientOptions,\n type HotRodClient,\n type HotRodClientOptions,\n type HotRodConnector,\n} from './client'\nexport {\n LAYOUT_VERSION,\n entryKey,\n entryKeyPrefix,\n namespacePrefix,\n tagKeyPrefix,\n tagShardKey,\n tagShardIndex,\n} from './layout'\n"],
5
+ "mappings": "AAAA,SAAS,UAAU,gCAAsE;AACzF,SAAS,WAAAA,gBAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;",
6
+ "names": ["default"]
7
+ }
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=infinispan-protocols.d.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }