@shiprev/server-sdk-node 0.1.0-beta.0 → 0.1.0-beta.1
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 +36 -13
- package/dist/auth/token-verifier.d.ts +16 -2
- package/dist/auth/token-verifier.js +34 -7
- package/dist/client/connection-supervisor.d.ts +32 -1
- package/dist/client/connection-supervisor.js +109 -6
- package/dist/client/shiprev-client.d.ts +34 -1
- package/dist/client/shiprev-client.js +137 -4
- package/dist/mirror/degradation.d.ts +22 -0
- package/dist/mirror/degradation.js +67 -0
- package/dist/mirror/entitlement-mirror.d.ts +15 -1
- package/dist/mirror/entitlement-mirror.js +36 -2
- package/dist/ruling/adjudicator.js +3 -11
- package/dist/transport/http.transport.d.ts +6 -1
- package/dist/transport/http.transport.js +21 -1
- package/dist/types.d.ts +62 -1
- package/dist/types.js +13 -1
- package/package.json +10 -11
package/README.md
CHANGED
|
@@ -69,18 +69,19 @@ A runnable version of this flow is the `examples/server-sdk-quickstart` example
|
|
|
69
69
|
|
|
70
70
|
`createClient(options)` and `new ShipRevClient(options)` take the same `ShipRevClientOptions`:
|
|
71
71
|
|
|
72
|
-
| Option | Default | Meaning
|
|
73
|
-
| :--------------------------- | :--------- |
|
|
74
|
-
| `base_url` | (required) | Base URL of the instance's core service; may include a path prefix. Trailing slashes are ignored
|
|
75
|
-
| `api_key` | (required) | SDK-scoped API key of the application
|
|
76
|
-
| `presets.cold_start` | `'deny'` | Ruling for **reads** when the mirror is empty and the instance is unreachable: `'allow'` or `'deny'`
|
|
77
|
-
| `presets.connect_timeout_ms` | `5000` | Timeout of every request to the instance
|
|
78
|
-
| `presets.reservation_ttl_s` | (service) | Default time-to-live of a reservation when `reserve()` does not pass one
|
|
79
|
-
| `buffer.batch_size` | `100` | Usage events sent per request; reaching it triggers a flush
|
|
80
|
-
| `buffer.flush_interval_ms` | `5000` | Background flush interval. `0` disables the timer; the timer never keeps the process alive
|
|
81
|
-
| `backlog` | memory | Where usage waits while it cannot be delivered; see [Persistence modes](#persistence-modes)
|
|
82
|
-
| `on_flush_failure` | | `(events, error) => void`, called when a batch could not be delivered (the events go to the backlog)
|
|
83
|
-
| `on_rejected` | | `(rejected) => void`, called with the events the service refused, each with a `reason`
|
|
72
|
+
| Option | Default | Meaning |
|
|
73
|
+
| :--------------------------- | :--------- | :--------------------------------------------------------------------------------------------------------------------------------------- |
|
|
74
|
+
| `base_url` | (required) | Base URL of the instance's core service; may include a path prefix. Trailing slashes are ignored |
|
|
75
|
+
| `api_key` | (required) | SDK-scoped API key of the application |
|
|
76
|
+
| `presets.cold_start` | `'deny'` | Ruling for **reads** when the mirror is empty and the instance is unreachable: `'allow'` or `'deny'` |
|
|
77
|
+
| `presets.connect_timeout_ms` | `5000` | Timeout of every request to the instance |
|
|
78
|
+
| `presets.reservation_ttl_s` | (service) | Default time-to-live of a reservation when `reserve()` does not pass one |
|
|
79
|
+
| `buffer.batch_size` | `100` | Usage events sent per request; reaching it triggers a flush |
|
|
80
|
+
| `buffer.flush_interval_ms` | `5000` | Background flush interval. `0` disables the timer; the timer never keeps the process alive |
|
|
81
|
+
| `backlog` | memory | Where usage waits while it cannot be delivered; see [Persistence modes](#persistence-modes) |
|
|
82
|
+
| `on_flush_failure` | | `(events, error) => void`, called when a batch could not be delivered (the events go to the backlog) |
|
|
83
|
+
| `on_rejected` | | `(rejected) => void`, called with the events the service refused, each with a `reason` |
|
|
84
|
+
| `on_level_change` | | `(organization_id, level) => void`, called when an organization's effective level changes; see [Degradation levels](#degradation-levels) |
|
|
84
85
|
|
|
85
86
|
## NestJS
|
|
86
87
|
|
|
@@ -163,6 +164,8 @@ export class ReportsController {
|
|
|
163
164
|
|
|
164
165
|
The expected issuer and application come from the service token the client obtains in `start()`; there is nothing to configure. Until the client has obtained one (never reached the instance), every token is refused with `not_ready`. Once known, the expectations are kept while the client is disconnected, and verification keeps working offline for every signing key already fetched. `TokenRejectedError` is exported from the main entry; its message never contains the token.
|
|
165
166
|
|
|
167
|
+
A token whose `kid` is not among the cached signing keys triggers one refetch of the instance's keys, but not within 30 seconds of the last successful fetch: inside that window it is refused (`Unknown key ID`) without any request, so forged tokens with random key IDs cannot multiply your traffic into requests to the instance. A failed fetch does not start the window. After the instance rotates its signing key, tokens signed with the new key may therefore be refused for up to 30 seconds after the previous fetch.
|
|
168
|
+
|
|
166
169
|
## Rulings and `operation`
|
|
167
170
|
|
|
168
171
|
Every ruling names its `operation`: `'read'` or `'write'`. It is required, because the two fail in opposite directions when the instance is unreachable: reads keep working from the last known entitlements, writes stop. Anything that consumes quota, changes state or costs money is a `write`. A missing or unknown `operation`, or a negative or non-finite `quantity`, is refused with `reason: 'invalid_request'`.
|
|
@@ -178,7 +181,7 @@ A `Ruling` is `{ allowed, source, reason?, remaining?, limit?, adjudicated_at }`
|
|
|
178
181
|
| `degraded` | Offline, ruled from the last snapshot |
|
|
179
182
|
| `client_default` | No basis for a ruling: invalid request, cold start offline, or online with nothing in the mirror |
|
|
180
183
|
|
|
181
|
-
Online rulings from the mirror compare `quantity` exactly against the remaining allowance, which the snapshot carries as fixed-point decimal strings. Beyond the remaining allowance
|
|
184
|
+
Online rulings from the mirror compare `quantity` exactly against the remaining allowance, which the snapshot carries as fixed-point decimal strings. Beyond the remaining allowance nothing is allowed locally, whatever the overage policy: whether credits (and, for `ALLOW_AND_BILL`, the wallet's overdraft limit) cover the write is state of the instance, so the local answer is a refusal with `reason: 'quota_exhausted'`, which `adjudicateAsync()` turns into a question to the instance and returns its ruling. When no ruling can be had the write stays refused. A capability the mirror does not hold is refused with `reason: 'capability_not_granted'` (which `adjudicateAsync()` turns into a question to the instance).
|
|
182
185
|
|
|
183
186
|
`guardWrite(options, action)` runs `action` only when a `write` ruling allows it, and otherwise throws `DisconnectedWriteError`.
|
|
184
187
|
|
|
@@ -228,6 +231,26 @@ Writes are refused whenever the push stream is down, even if other requests to t
|
|
|
228
231
|
|
|
229
232
|
`setOnline(false)` closes the push stream and suspends reconnection until `setOnline(true)`, which sets `LIVE` at once and resumes; on a started client the next connection attempt then corrects the state. Both are for fault injection and tests. `loadSnapshot(snapshot)` seeds the mirror without the network (a `COLD_OFFLINE` client becomes `DISCONNECTED`).
|
|
230
233
|
|
|
234
|
+
## Degradation levels
|
|
235
|
+
|
|
236
|
+
Every organization entry of the snapshot carries two fields the instance computes: `degradation_level`, one of `NONE`, `RESTRICT_NEW`, `RESTRICT_USAGE`, `RESTRICT_READ` and `SUSPENDED` (strictly increasing), and `valid_until`, the time until which the entry may be used without a newer answer. An instance sets the level from its own rules (for example a buyer's unpaid invoices); at `SUSPENDED` the entry's `items` is empty, so nothing is granted. Instances that predate the fields leave them out.
|
|
237
|
+
|
|
238
|
+
`effectiveLevel(organizationId)` combines them with the connection, synchronously and without I/O, into `{ level, source, expired }` (`undefined` when the mirror does not hold the organization):
|
|
239
|
+
|
|
240
|
+
| The client observes | `level` | `source` | `expired` |
|
|
241
|
+
| :----------------------------------------------------- | :----------------------------------------------------- | :----------- | :-------- |
|
|
242
|
+
| `LIVE` (the instance answers) | The entry's level | `'answer'` | `false` |
|
|
243
|
+
| Not `LIVE`, before the entry's `valid_until` | The entry's level | `'degraded'` | `false` |
|
|
244
|
+
| Not `LIVE`, at or after `valid_until` (or none usable) | The entry's level, raised to `RESTRICT_USAGE` at least | `'degraded'` | `true` |
|
|
245
|
+
|
|
246
|
+
A level the client does not know (another string, or not a string) reads as `RESTRICT_USAGE`, never looser. The level does not change `adjudicate()`, `adjudicateAsync()` or `guardWrite()`: a disconnected write is refused whatever the level; what a level blocks in your service is your decision.
|
|
247
|
+
|
|
248
|
+
While `LIVE`, once half of an entry's validity has passed without a newer entry, the client pulls that organization once to renew it (never more than once per entry, never on a fixed period).
|
|
249
|
+
|
|
250
|
+
`refresh(organizationId, { timeout_ms? })` pulls one organization now, sharing a pull already in flight for it, and resolves with the answer's level (`source: 'answer'`); when the pull fails or does not finish within `timeout_ms` (default `presets.connect_timeout_ms`) it resolves with `effectiveLevel()` as it stands. Use it before refusing an action on a level, so that a change at the instance applies within the action.
|
|
251
|
+
|
|
252
|
+
`sendUsage(events)` sends one batch at once, outside the buffer and the backlog, and resolves with `{ accepted_count, duplicates_dropped, rejected }`. Quantities may be decimal strings, sent unchanged. It throws `UsageDeliveryError` when the batch did not get through (network error, timeout, `5xx`); any other refusal throws as it came. Sending the same batch again is safe, as events are deduplicated by `usage_event_id`. It is for callers that keep their own durable queue; everyone else uses `reportUsage()`.
|
|
253
|
+
|
|
231
254
|
## Persistence modes
|
|
232
255
|
|
|
233
256
|
`backlog.mode` chooses where undeliverable usage waits:
|
|
@@ -9,21 +9,35 @@ export interface TokenExpectations {
|
|
|
9
9
|
projectId: string;
|
|
10
10
|
}
|
|
11
11
|
export declare function jwkToPem(jwk: JwksKey): string;
|
|
12
|
+
/**
|
|
13
|
+
* After a successful JWKS fetch, a token with an unknown `kid` does not trigger another fetch for
|
|
14
|
+
* this long; it is refused instead. Without it, an anonymous caller could turn every forged token
|
|
15
|
+
* carrying a random `kid` into one request to the instance. A key rotated in during this window is
|
|
16
|
+
* accepted at most this long after the previous fetch.
|
|
17
|
+
*/
|
|
18
|
+
export declare const JWKS_REFRESH_COOLDOWN_MS = 30000;
|
|
12
19
|
export declare class TokenVerifier {
|
|
13
20
|
private readonly transport;
|
|
14
21
|
private readonly publicKeyCache;
|
|
22
|
+
/** `Date.now()` of the last successful JWKS fetch; failed fetches do not set it. */
|
|
23
|
+
private lastRefreshAt;
|
|
24
|
+
private inFlightRefresh;
|
|
15
25
|
constructor(transport: HttpTransport);
|
|
16
26
|
/**
|
|
17
|
-
* Refreshes the local in-memory public key cache from the JWKS endpoint
|
|
27
|
+
* Refreshes the local in-memory public key cache from the JWKS endpoint. Always fetches (no
|
|
28
|
+
* cooldown); concurrent calls share one request. A success starts the unknown-`kid` cooldown.
|
|
18
29
|
*/
|
|
19
30
|
refreshKeys(): Promise<void>;
|
|
31
|
+
private fetchKeys;
|
|
32
|
+
private inRefreshCooldown;
|
|
20
33
|
/**
|
|
21
34
|
* Directly caches a key in memory (e.g. for testing or preloading)
|
|
22
35
|
*/
|
|
23
36
|
setPublicKey(kid: string, pem: string): void;
|
|
24
37
|
/**
|
|
25
38
|
* Verifies an RS256 JWT token locally, extracting the subject and isolation keys.
|
|
26
|
-
* If the kid is unknown in cache, it triggers a single JWKS refresh
|
|
39
|
+
* If the kid is unknown in cache, it triggers a single JWKS refresh, unless the last successful
|
|
40
|
+
* refresh is less than `JWKS_REFRESH_COOLDOWN_MS` old, in which case the token is refused at once.
|
|
27
41
|
*
|
|
28
42
|
* With `expectations` (or `null`, meaning they are not known yet), the token must also be a buyer
|
|
29
43
|
* session token of that issuer and application; the checks run after the signature, in the order
|
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.TokenVerifier = void 0;
|
|
36
|
+
exports.TokenVerifier = exports.JWKS_REFRESH_COOLDOWN_MS = void 0;
|
|
37
37
|
exports.jwkToPem = jwkToPem;
|
|
38
38
|
exports.expectationsFromMachineToken = expectationsFromMachineToken;
|
|
39
39
|
exports.expiryOfToken = expiryOfToken;
|
|
@@ -59,21 +59,44 @@ function jwkToPem(jwk) {
|
|
|
59
59
|
});
|
|
60
60
|
return keyObj.export({ type: 'spki', format: 'pem' });
|
|
61
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* After a successful JWKS fetch, a token with an unknown `kid` does not trigger another fetch for
|
|
64
|
+
* this long; it is refused instead. Without it, an anonymous caller could turn every forged token
|
|
65
|
+
* carrying a random `kid` into one request to the instance. A key rotated in during this window is
|
|
66
|
+
* accepted at most this long after the previous fetch.
|
|
67
|
+
*/
|
|
68
|
+
exports.JWKS_REFRESH_COOLDOWN_MS = 30_000;
|
|
62
69
|
class TokenVerifier {
|
|
63
70
|
transport;
|
|
64
71
|
publicKeyCache = new Map();
|
|
72
|
+
/** `Date.now()` of the last successful JWKS fetch; failed fetches do not set it. */
|
|
73
|
+
lastRefreshAt = null;
|
|
74
|
+
inFlightRefresh = null;
|
|
65
75
|
constructor(transport) {
|
|
66
76
|
this.transport = transport;
|
|
67
77
|
}
|
|
68
78
|
/**
|
|
69
|
-
* Refreshes the local in-memory public key cache from the JWKS endpoint
|
|
79
|
+
* Refreshes the local in-memory public key cache from the JWKS endpoint. Always fetches (no
|
|
80
|
+
* cooldown); concurrent calls share one request. A success starts the unknown-`kid` cooldown.
|
|
70
81
|
*/
|
|
71
82
|
async refreshKeys() {
|
|
83
|
+
if (!this.inFlightRefresh) {
|
|
84
|
+
this.inFlightRefresh = this.fetchKeys().finally(() => {
|
|
85
|
+
this.inFlightRefresh = null;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return this.inFlightRefresh;
|
|
89
|
+
}
|
|
90
|
+
async fetchKeys() {
|
|
72
91
|
const jwks = await this.transport.fetchJwks();
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
this.publicKeyCache.set(
|
|
92
|
+
const pems = jwks.keys.map((key) => [key.kid, jwkToPem(key)]);
|
|
93
|
+
for (const [kid, pem] of pems) {
|
|
94
|
+
this.publicKeyCache.set(kid, pem);
|
|
76
95
|
}
|
|
96
|
+
this.lastRefreshAt = Date.now();
|
|
97
|
+
}
|
|
98
|
+
inRefreshCooldown() {
|
|
99
|
+
return this.lastRefreshAt !== null && Date.now() - this.lastRefreshAt < exports.JWKS_REFRESH_COOLDOWN_MS;
|
|
77
100
|
}
|
|
78
101
|
/**
|
|
79
102
|
* Directly caches a key in memory (e.g. for testing or preloading)
|
|
@@ -83,7 +106,8 @@ class TokenVerifier {
|
|
|
83
106
|
}
|
|
84
107
|
/**
|
|
85
108
|
* Verifies an RS256 JWT token locally, extracting the subject and isolation keys.
|
|
86
|
-
* If the kid is unknown in cache, it triggers a single JWKS refresh
|
|
109
|
+
* If the kid is unknown in cache, it triggers a single JWKS refresh, unless the last successful
|
|
110
|
+
* refresh is less than `JWKS_REFRESH_COOLDOWN_MS` old, in which case the token is refused at once.
|
|
87
111
|
*
|
|
88
112
|
* With `expectations` (or `null`, meaning they are not known yet), the token must also be a buyer
|
|
89
113
|
* session token of that issuer and application; the checks run after the signature, in the order
|
|
@@ -116,8 +140,11 @@ class TokenVerifier {
|
|
|
116
140
|
}
|
|
117
141
|
// Lookup public key from local cache
|
|
118
142
|
let publicKeyPem = this.publicKeyCache.get(kid);
|
|
119
|
-
// Cache miss / key rotation: refresh keys once
|
|
143
|
+
// Cache miss / key rotation: refresh keys once, outside the cooldown only
|
|
120
144
|
if (!publicKeyPem) {
|
|
145
|
+
if (this.inRefreshCooldown()) {
|
|
146
|
+
throw new Error(`Unknown key ID: kid=${kid}`);
|
|
147
|
+
}
|
|
121
148
|
await this.refreshKeys();
|
|
122
149
|
publicKeyPem = this.publicKeyCache.get(kid);
|
|
123
150
|
if (!publicKeyPem) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EntitlementMirror } from '../mirror/entitlement-mirror';
|
|
2
2
|
import { HttpTransport } from '../transport/http.transport';
|
|
3
|
+
import { OrganizationSnapshot, Snapshot } from '../types';
|
|
3
4
|
/**
|
|
4
5
|
* Keeps a started client connected to its instance, from `start()` to `stop()`:
|
|
5
6
|
*
|
|
@@ -12,7 +13,9 @@ import { HttpTransport } from '../transport/http.transport';
|
|
|
12
13
|
* new one is ready, without pulling; on an unplanned break reconnects once at once, then backs
|
|
13
14
|
* off (1, 2, 4, 8, 16, 30 s, ±20 %);
|
|
14
15
|
* - turns `snapshot.changed` into per-organization refills (at most one in flight per organization)
|
|
15
|
-
* and `snapshot.resync` into a full pull
|
|
16
|
+
* and `snapshot.resync` into a full pull;
|
|
17
|
+
* - while online, renews an organization entry that carries `valid_until` once half of its validity has passed
|
|
18
|
+
* without a newer entry, with one pull of that organization. It never pulls on a fixed period.
|
|
16
19
|
*
|
|
17
20
|
* Every timer is unref'd, so the supervisor never keeps the host process alive.
|
|
18
21
|
*/
|
|
@@ -31,6 +34,18 @@ export interface SupervisorHost {
|
|
|
31
34
|
/** Delivers buffered and backlogged usage. */
|
|
32
35
|
flush(): Promise<void>;
|
|
33
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* What one per-organization pull did to the mirror: `applied` (the answer's entry is now the mirror's entry),
|
|
39
|
+
* `removed` (the answer no longer holds the organization and the mirror dropped it), or `ignored` (the answer
|
|
40
|
+
* was not used: a newer entry was already held or arrived meanwhile, an unsupported schema, or the client was
|
|
41
|
+
* stopped or paused meanwhile). Only an applied or removed pull is an answer about the organization.
|
|
42
|
+
*/
|
|
43
|
+
export interface OrganizationPull {
|
|
44
|
+
envelope: Snapshot;
|
|
45
|
+
outcome: 'applied' | 'removed' | 'ignored';
|
|
46
|
+
/** The mirror's entry after an applied pull. */
|
|
47
|
+
entry?: OrganizationSnapshot;
|
|
48
|
+
}
|
|
34
49
|
export declare class ConnectionSupervisor {
|
|
35
50
|
private readonly host;
|
|
36
51
|
private token;
|
|
@@ -55,8 +70,13 @@ export declare class ConnectionSupervisor {
|
|
|
55
70
|
private renewTimer;
|
|
56
71
|
private reconnectTimer;
|
|
57
72
|
private watchdogTimer;
|
|
73
|
+
private renewalTimer;
|
|
58
74
|
private readonly refillTargets;
|
|
59
75
|
private readonly refillsInFlight;
|
|
76
|
+
/** Per-organization pulls in flight, shared by refills, renewals and `refresh()`. */
|
|
77
|
+
private readonly organizationPulls;
|
|
78
|
+
/** Organizations whose last renewal pull failed, with the time a renewal may be tried again. */
|
|
79
|
+
private readonly renewalRetryAt;
|
|
60
80
|
constructor(host: SupervisorHost);
|
|
61
81
|
/** The machine token in use, or `null`. */
|
|
62
82
|
currentToken(): string | null;
|
|
@@ -109,6 +129,17 @@ export declare class ConnectionSupervisor {
|
|
|
109
129
|
private onChanged;
|
|
110
130
|
/** Refills one organization until the mirror reaches the highest announced revision. */
|
|
111
131
|
private refill;
|
|
132
|
+
/**
|
|
133
|
+
* One pull of one organization, shared by every concurrent caller, merged into the mirror (or removing the
|
|
134
|
+
* organization when the answer no longer holds it). A pull that finishes after `stop()` or `pause()` leaves
|
|
135
|
+
* the mirror as it is.
|
|
136
|
+
*/
|
|
137
|
+
pullOrganization(organizationId: string): Promise<OrganizationPull>;
|
|
138
|
+
/** Re-arms the renewal timer for the earliest entry due; nothing while offline. Called on every mirror change. */
|
|
139
|
+
scheduleRenewals(): void;
|
|
140
|
+
/** Halfway between receiving an entry and its `valid_until`; undefined for an entry without a usable one. */
|
|
141
|
+
private renewalDue;
|
|
142
|
+
private renewDueEntries;
|
|
112
143
|
/** Full pull: replaces the whole mirror. */
|
|
113
144
|
private pull;
|
|
114
145
|
/** Drops the stream, every timer and any attempt in flight. */
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ConnectionSupervisor = void 0;
|
|
4
4
|
const token_verifier_1 = require("../auth/token-verifier");
|
|
5
|
+
const degradation_1 = require("../mirror/degradation");
|
|
6
|
+
const entitlement_mirror_1 = require("../mirror/entitlement-mirror");
|
|
5
7
|
const event_stream_1 = require("../transport/event-stream");
|
|
6
8
|
const http_transport_1 = require("../transport/http.transport");
|
|
7
9
|
/** Retry interval while the instance refuses the API key (401 or 403 on the token exchange). */
|
|
@@ -9,6 +11,10 @@ const REFUSED_RETRY_MS = 30_000;
|
|
|
9
11
|
const BACKOFF_STEPS_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000];
|
|
10
12
|
const RENEW_AT = 0.8;
|
|
11
13
|
const HEARTBEAT_TIMEOUT_FACTOR = 3;
|
|
14
|
+
/** Shortest time between two renewals of the same entry. */
|
|
15
|
+
const MIN_RENEWAL_SPACING_MS = 10_000;
|
|
16
|
+
/** Wait before renewing an entry again after a renewal pull failed. */
|
|
17
|
+
const RENEWAL_RETRY_MS = 30_000;
|
|
12
18
|
function backoffDelay(step) {
|
|
13
19
|
const base = BACKOFF_STEPS_MS[Math.min(step, BACKOFF_STEPS_MS.length - 1)];
|
|
14
20
|
return Math.round(base * (0.8 + Math.random() * 0.4));
|
|
@@ -42,8 +48,13 @@ class ConnectionSupervisor {
|
|
|
42
48
|
renewTimer = null;
|
|
43
49
|
reconnectTimer = null;
|
|
44
50
|
watchdogTimer = null;
|
|
51
|
+
renewalTimer = null;
|
|
45
52
|
refillTargets = new Map();
|
|
46
53
|
refillsInFlight = new Set();
|
|
54
|
+
/** Per-organization pulls in flight, shared by refills, renewals and `refresh()`. */
|
|
55
|
+
organizationPulls = new Map();
|
|
56
|
+
/** Organizations whose last renewal pull failed, with the time a renewal may be tried again. */
|
|
57
|
+
renewalRetryAt = new Map();
|
|
47
58
|
constructor(host) {
|
|
48
59
|
this.host = host;
|
|
49
60
|
}
|
|
@@ -218,6 +229,7 @@ class ConnectionSupervisor {
|
|
|
218
229
|
this.backoffStep = 0;
|
|
219
230
|
this.host.setOnline(true);
|
|
220
231
|
this.armWatchdog();
|
|
232
|
+
this.scheduleRenewals();
|
|
221
233
|
if (flush) {
|
|
222
234
|
void this.host.flush().catch(() => undefined);
|
|
223
235
|
}
|
|
@@ -229,6 +241,7 @@ class ConnectionSupervisor {
|
|
|
229
241
|
this.stream = null;
|
|
230
242
|
}
|
|
231
243
|
this.clearTimer('watchdogTimer');
|
|
244
|
+
this.clearTimer('renewalTimer');
|
|
232
245
|
this.host.setOnline(false);
|
|
233
246
|
}
|
|
234
247
|
/** An unplanned break of the active stream: one immediate reconnect, still LIVE meanwhile. */
|
|
@@ -487,17 +500,17 @@ class ConnectionSupervisor {
|
|
|
487
500
|
this.refillsInFlight.add(organizationId);
|
|
488
501
|
try {
|
|
489
502
|
for (;;) {
|
|
490
|
-
const envelope = await this.
|
|
503
|
+
const { envelope, outcome } = await this.pullOrganization(organizationId);
|
|
491
504
|
if (!this.running)
|
|
492
505
|
return;
|
|
493
|
-
if (envelope.organizations
|
|
494
|
-
this.host.mirror.mergeSnapshot(envelope);
|
|
495
|
-
}
|
|
496
|
-
else {
|
|
497
|
-
this.host.mirror.removeOrganization(organizationId);
|
|
506
|
+
if (!envelope.organizations || !(organizationId in envelope.organizations)) {
|
|
498
507
|
this.refillTargets.delete(organizationId);
|
|
499
508
|
return;
|
|
500
509
|
}
|
|
510
|
+
// An answer the mirror did not take (stale or unsupported) is not asked again at once; the target
|
|
511
|
+
// stays for the next notification or full pull.
|
|
512
|
+
if (outcome === 'ignored')
|
|
513
|
+
return;
|
|
501
514
|
const target = this.refillTargets.get(organizationId) ?? 0;
|
|
502
515
|
if ((this.host.mirror.getOrganizationRevision(organizationId) ?? 0) >= target) {
|
|
503
516
|
this.refillTargets.delete(organizationId);
|
|
@@ -512,6 +525,95 @@ class ConnectionSupervisor {
|
|
|
512
525
|
this.refillsInFlight.delete(organizationId);
|
|
513
526
|
}
|
|
514
527
|
}
|
|
528
|
+
/**
|
|
529
|
+
* One pull of one organization, shared by every concurrent caller, merged into the mirror (or removing the
|
|
530
|
+
* organization when the answer no longer holds it). A pull that finishes after `stop()` or `pause()` leaves
|
|
531
|
+
* the mirror as it is.
|
|
532
|
+
*/
|
|
533
|
+
pullOrganization(organizationId) {
|
|
534
|
+
const inFlight = this.organizationPulls.get(organizationId);
|
|
535
|
+
if (inFlight)
|
|
536
|
+
return inFlight;
|
|
537
|
+
const generation = this.generation;
|
|
538
|
+
const pull = (async () => {
|
|
539
|
+
const heldBefore = this.host.mirror.getOrganization(organizationId);
|
|
540
|
+
const envelope = await this.authorized((token) => this.host.transport.fetchSnapshot(token, organizationId));
|
|
541
|
+
const usable = generation === this.generation &&
|
|
542
|
+
typeof envelope?.schema_version === 'number' &&
|
|
543
|
+
envelope.schema_version <= entitlement_mirror_1.MAX_SUPPORTED_SCHEMA_VERSION;
|
|
544
|
+
if (!usable)
|
|
545
|
+
return { envelope, outcome: 'ignored' };
|
|
546
|
+
const answered = envelope.organizations?.[organizationId];
|
|
547
|
+
if (answered) {
|
|
548
|
+
this.host.mirror.mergeSnapshot(envelope);
|
|
549
|
+
const held = this.host.mirror.getOrganization(organizationId);
|
|
550
|
+
return held === answered ? { envelope, outcome: 'applied', entry: held } : { envelope, outcome: 'ignored' };
|
|
551
|
+
}
|
|
552
|
+
// Drop the organization only if the mirror still holds what it held when the pull started: a newer entry
|
|
553
|
+
// that arrived meanwhile is not removed by an older answer.
|
|
554
|
+
if (this.host.mirror.getOrganization(organizationId) !== heldBefore)
|
|
555
|
+
return { envelope, outcome: 'ignored' };
|
|
556
|
+
this.host.mirror.removeOrganization(organizationId);
|
|
557
|
+
return { envelope, outcome: 'removed' };
|
|
558
|
+
})();
|
|
559
|
+
this.organizationPulls.set(organizationId, pull);
|
|
560
|
+
const clear = () => {
|
|
561
|
+
if (this.organizationPulls.get(organizationId) === pull)
|
|
562
|
+
this.organizationPulls.delete(organizationId);
|
|
563
|
+
};
|
|
564
|
+
void pull.then(clear, clear);
|
|
565
|
+
return pull;
|
|
566
|
+
}
|
|
567
|
+
// ─── Renewal of entries with a validity ───────────────────────────────────
|
|
568
|
+
/** Re-arms the renewal timer for the earliest entry due; nothing while offline. Called on every mirror change. */
|
|
569
|
+
scheduleRenewals() {
|
|
570
|
+
this.clearTimer('renewalTimer');
|
|
571
|
+
if (!this.running || this.paused || !this.live)
|
|
572
|
+
return;
|
|
573
|
+
let next = Number.POSITIVE_INFINITY;
|
|
574
|
+
for (const organizationId of this.host.mirror.organizationIds()) {
|
|
575
|
+
const due = this.renewalDue(organizationId);
|
|
576
|
+
if (due !== undefined)
|
|
577
|
+
next = Math.min(next, due);
|
|
578
|
+
}
|
|
579
|
+
if (next === Number.POSITIVE_INFINITY)
|
|
580
|
+
return;
|
|
581
|
+
this.renewalTimer = unrefTimer(() => {
|
|
582
|
+
this.renewalTimer = null;
|
|
583
|
+
this.renewDueEntries();
|
|
584
|
+
}, next - Date.now());
|
|
585
|
+
}
|
|
586
|
+
/** Halfway between receiving an entry and its `valid_until`; undefined for an entry without a usable one. */
|
|
587
|
+
renewalDue(organizationId) {
|
|
588
|
+
const entry = this.host.mirror.getOrganization(organizationId);
|
|
589
|
+
const receivedAt = this.host.mirror.getReceivedAt(organizationId);
|
|
590
|
+
if (!entry || receivedAt === undefined)
|
|
591
|
+
return undefined;
|
|
592
|
+
const validUntil = (0, degradation_1.validUntilOf)(entry);
|
|
593
|
+
if (validUntil === undefined || validUntil <= receivedAt)
|
|
594
|
+
return undefined;
|
|
595
|
+
const due = Math.max(receivedAt + (validUntil - receivedAt) / 2, receivedAt + MIN_RENEWAL_SPACING_MS);
|
|
596
|
+
return Math.max(due, this.renewalRetryAt.get(organizationId) ?? 0);
|
|
597
|
+
}
|
|
598
|
+
renewDueEntries() {
|
|
599
|
+
if (!this.running || this.paused || !this.live)
|
|
600
|
+
return;
|
|
601
|
+
const now = Date.now();
|
|
602
|
+
for (const organizationId of this.host.mirror.organizationIds()) {
|
|
603
|
+
const due = this.renewalDue(organizationId);
|
|
604
|
+
if (due === undefined || due > now)
|
|
605
|
+
continue;
|
|
606
|
+
this.renewalRetryAt.set(organizationId, now + RENEWAL_RETRY_MS);
|
|
607
|
+
// The retry time set above stays unless the renewal was taken: a stale or unsupported answer does not
|
|
608
|
+
// move the entry's receipt time, and renewing it again at once would pull without end.
|
|
609
|
+
void this.pullOrganization(organizationId).then(({ outcome }) => {
|
|
610
|
+
if (outcome !== 'ignored')
|
|
611
|
+
this.renewalRetryAt.delete(organizationId);
|
|
612
|
+
this.scheduleRenewals();
|
|
613
|
+
}, () => this.scheduleRenewals());
|
|
614
|
+
}
|
|
615
|
+
this.scheduleRenewals();
|
|
616
|
+
}
|
|
515
617
|
/** Full pull: replaces the whole mirror. */
|
|
516
618
|
async pull() {
|
|
517
619
|
const snapshot = await this.authorized((token) => this.host.transport.fetchSnapshot(token));
|
|
@@ -535,6 +637,7 @@ class ConnectionSupervisor {
|
|
|
535
637
|
this.clearTimer('renewTimer');
|
|
536
638
|
this.clearTimer('reconnectTimer');
|
|
537
639
|
this.clearTimer('watchdogTimer');
|
|
640
|
+
this.clearTimer('renewalTimer');
|
|
538
641
|
}
|
|
539
642
|
clearTimer(name) {
|
|
540
643
|
const timer = this[name];
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { UsageBuffer } from '../metering/usage-buffer';
|
|
2
2
|
import { HttpTransport } from '../transport/http.transport';
|
|
3
|
-
import { AdjudicateOptions, ClientState, ConfirmReservationResult, ReleaseReservationResult, ReservationResult, ReserveOptions, Ruling, ShipRevClientOptions, Snapshot, TokenClaims, UsageEventItem } from '../types';
|
|
3
|
+
import { AdjudicateOptions, ClientState, ConfirmReservationResult, EffectiveLevel, ReleaseReservationResult, ReservationResult, ReserveOptions, Ruling, ShipRevClientOptions, Snapshot, TokenClaims, UsageEventItem, UsageSendEvent, UsageSendResult } from '../types';
|
|
4
4
|
export declare class ShipRevClient {
|
|
5
5
|
private readonly options;
|
|
6
6
|
private readonly transport;
|
|
@@ -16,6 +16,10 @@ export declare class ShipRevClient {
|
|
|
16
16
|
private expectations;
|
|
17
17
|
/** Amounts reserved by this client, so `confirm()` without an amount confirms what was reserved. */
|
|
18
18
|
private readonly reservedAmounts;
|
|
19
|
+
/** Effective levels last reported through `on_level_change`. */
|
|
20
|
+
private readonly reportedLevels;
|
|
21
|
+
/** Fires when the earliest `valid_until` passes while disconnected, to report the expiry. */
|
|
22
|
+
private expiryTimer;
|
|
19
23
|
constructor(options: ShipRevClientOptions);
|
|
20
24
|
/**
|
|
21
25
|
* Connects the client: fetches the signing keys, exchanges the API key for a service token, opens
|
|
@@ -54,6 +58,30 @@ export declare class ShipRevClient {
|
|
|
54
58
|
* If local mirror misses the organization or rule and client is online, queries core service and backfills mirror.
|
|
55
59
|
*/
|
|
56
60
|
adjudicateAsync(options: AdjudicateOptions): Promise<Ruling>;
|
|
61
|
+
/**
|
|
62
|
+
* The effective degradation level of an organization: the level of the mirror entry while the instance
|
|
63
|
+
* answers; without an answer, the entry's level until its `valid_until`, then at least `RESTRICT_USAGE`
|
|
64
|
+
* (marked `expired`). `undefined` when the mirror does not hold the organization. Synchronous, no I/O.
|
|
65
|
+
*
|
|
66
|
+
* It does not change `adjudicate()` or `guardWrite()`: a disconnected write is refused whatever the level.
|
|
67
|
+
*/
|
|
68
|
+
effectiveLevel(organizationId: string): EffectiveLevel | undefined;
|
|
69
|
+
/**
|
|
70
|
+
* Pulls one organization now (sharing a pull already in flight for it) and resolves with the level of the
|
|
71
|
+
* answer, `source: 'answer'`. When the pull fails or does not finish within `timeout_ms` (default: the
|
|
72
|
+
* connect timeout), resolves with `effectiveLevel()` as it stands. `undefined` when the instance no longer
|
|
73
|
+
* holds the organization, or the mirror never did.
|
|
74
|
+
*/
|
|
75
|
+
refresh(organizationId: string, options?: {
|
|
76
|
+
timeout_ms?: number;
|
|
77
|
+
}): Promise<EffectiveLevel | undefined>;
|
|
78
|
+
/**
|
|
79
|
+
* Sends a batch of usage events at once, outside the buffer and the backlog, and resolves with what the
|
|
80
|
+
* instance did with each. A 401 renews the token once, as every request does. Throws `UsageDeliveryError`
|
|
81
|
+
* when the batch did not reach the instance or it failed to process it (network error, timeout, 5xx); any
|
|
82
|
+
* other refusal throws as it came. Sending the same batch again is safe: events are deduplicated by key.
|
|
83
|
+
*/
|
|
84
|
+
sendUsage(events: UsageSendEvent[]): Promise<UsageSendResult>;
|
|
57
85
|
/**
|
|
58
86
|
* Guard for write operations (fail-closed).
|
|
59
87
|
* Intercepts action if write operation is denied (e.g. disconnected).
|
|
@@ -101,6 +129,11 @@ export declare class ShipRevClient {
|
|
|
101
129
|
getUsageBuffer(): UsageBuffer;
|
|
102
130
|
getTransport(): HttpTransport;
|
|
103
131
|
private applyOnline;
|
|
132
|
+
private onMirrorChange;
|
|
133
|
+
/** Reports every organization whose effective level differs from what was last reported. */
|
|
134
|
+
private notifyLevels;
|
|
135
|
+
/** While disconnected, wakes up when the earliest entry still valid expires, to report it. */
|
|
136
|
+
private armExpiryTimer;
|
|
104
137
|
private learnExpectations;
|
|
105
138
|
private refillOrganization;
|
|
106
139
|
}
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.ShipRevClient = void 0;
|
|
4
4
|
const token_verifier_1 = require("../auth/token-verifier");
|
|
5
5
|
const usage_buffer_1 = require("../metering/usage-buffer");
|
|
6
|
+
const degradation_1 = require("../mirror/degradation");
|
|
6
7
|
const entitlement_mirror_1 = require("../mirror/entitlement-mirror");
|
|
7
8
|
const adjudicator_1 = require("../ruling/adjudicator");
|
|
8
9
|
const http_transport_1 = require("../transport/http.transport");
|
|
@@ -23,6 +24,10 @@ class ShipRevClient {
|
|
|
23
24
|
expectations = null;
|
|
24
25
|
/** Amounts reserved by this client, so `confirm()` without an amount confirms what was reserved. */
|
|
25
26
|
reservedAmounts = new Map();
|
|
27
|
+
/** Effective levels last reported through `on_level_change`. */
|
|
28
|
+
reportedLevels = new Map();
|
|
29
|
+
/** Fires when the earliest `valid_until` passes while disconnected, to report the expiry. */
|
|
30
|
+
expiryTimer = null;
|
|
26
31
|
constructor(options) {
|
|
27
32
|
this.options = options;
|
|
28
33
|
this.transport = new http_transport_1.HttpTransport({
|
|
@@ -30,7 +35,7 @@ class ShipRevClient {
|
|
|
30
35
|
connectTimeoutMs: options.presets?.connect_timeout_ms,
|
|
31
36
|
});
|
|
32
37
|
this.tokenVerifier = new token_verifier_1.TokenVerifier(this.transport);
|
|
33
|
-
this.mirror = new entitlement_mirror_1.EntitlementMirror();
|
|
38
|
+
this.mirror = new entitlement_mirror_1.EntitlementMirror((organizationIds) => this.onMirrorChange(organizationIds));
|
|
34
39
|
this.adjudicator = new adjudicator_1.Adjudicator(this.mirror, options.presets);
|
|
35
40
|
this.supervisor = new connection_supervisor_1.ConnectionSupervisor({
|
|
36
41
|
transport: this.transport,
|
|
@@ -74,6 +79,10 @@ class ShipRevClient {
|
|
|
74
79
|
*/
|
|
75
80
|
async stop() {
|
|
76
81
|
this.supervisor.stop();
|
|
82
|
+
if (this.expiryTimer) {
|
|
83
|
+
clearTimeout(this.expiryTimer);
|
|
84
|
+
this.expiryTimer = null;
|
|
85
|
+
}
|
|
77
86
|
await this.usageBuffer.stop();
|
|
78
87
|
this.active = false;
|
|
79
88
|
this.isOnline = false;
|
|
@@ -115,9 +124,11 @@ class ShipRevClient {
|
|
|
115
124
|
if (ruling.allowed || ruling.source === 'degraded' || !this.isOnline) {
|
|
116
125
|
return ruling;
|
|
117
126
|
}
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
|
|
127
|
+
// Two cases are not decided by the mirror, and the service is asked for an authoritative ruling:
|
|
128
|
+
// the mirror misses the organization or capability, or the write goes beyond the allowance the mirror
|
|
129
|
+
// counts (credits and overdraft are the service's state). The mirror's refusal stands when no ruling comes.
|
|
130
|
+
const beyondAllowance = ruling.reason === 'quota_exhausted' && ruling.source === 'realtime';
|
|
131
|
+
if (this.supervisor.currentToken() && (ruling.reason === 'capability_not_granted' || beyondAllowance)) {
|
|
121
132
|
try {
|
|
122
133
|
const remote = await this.supervisor.authorized((token) => this.transport.lookupAdjudication({
|
|
123
134
|
organization_id: options.organization_id,
|
|
@@ -144,6 +155,65 @@ class ShipRevClient {
|
|
|
144
155
|
}
|
|
145
156
|
return ruling;
|
|
146
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* The effective degradation level of an organization: the level of the mirror entry while the instance
|
|
160
|
+
* answers; without an answer, the entry's level until its `valid_until`, then at least `RESTRICT_USAGE`
|
|
161
|
+
* (marked `expired`). `undefined` when the mirror does not hold the organization. Synchronous, no I/O.
|
|
162
|
+
*
|
|
163
|
+
* It does not change `adjudicate()` or `guardWrite()`: a disconnected write is refused whatever the level.
|
|
164
|
+
*/
|
|
165
|
+
effectiveLevel(organizationId) {
|
|
166
|
+
const entry = this.mirror.getOrganization(organizationId);
|
|
167
|
+
return entry ? (0, degradation_1.combineLevel)(entry, this.isOnline, Date.now()) : undefined;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Pulls one organization now (sharing a pull already in flight for it) and resolves with the level of the
|
|
171
|
+
* answer, `source: 'answer'`. When the pull fails or does not finish within `timeout_ms` (default: the
|
|
172
|
+
* connect timeout), resolves with `effectiveLevel()` as it stands. `undefined` when the instance no longer
|
|
173
|
+
* holds the organization, or the mirror never did.
|
|
174
|
+
*/
|
|
175
|
+
async refresh(organizationId, options) {
|
|
176
|
+
const timeoutMs = options?.timeout_ms ?? this.options.presets?.connect_timeout_ms ?? 5000;
|
|
177
|
+
let timer;
|
|
178
|
+
try {
|
|
179
|
+
const pulled = await Promise.race([
|
|
180
|
+
this.supervisor.pullOrganization(organizationId),
|
|
181
|
+
new Promise((_resolve, reject) => {
|
|
182
|
+
timer = setTimeout(() => reject(new Error('refresh timed out')), timeoutMs);
|
|
183
|
+
timer.unref();
|
|
184
|
+
}),
|
|
185
|
+
]);
|
|
186
|
+
// Only an answer the mirror took is an answer; a stale or unsupported one leaves the level as it stands.
|
|
187
|
+
if (pulled.outcome === 'applied' && pulled.entry)
|
|
188
|
+
return (0, degradation_1.combineLevel)(pulled.entry, true, Date.now());
|
|
189
|
+
if (pulled.outcome === 'removed')
|
|
190
|
+
return undefined;
|
|
191
|
+
return this.effectiveLevel(organizationId);
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
return this.effectiveLevel(organizationId);
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
if (timer)
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Sends a batch of usage events at once, outside the buffer and the backlog, and resolves with what the
|
|
203
|
+
* instance did with each. A 401 renews the token once, as every request does. Throws `UsageDeliveryError`
|
|
204
|
+
* when the batch did not reach the instance or it failed to process it (network error, timeout, 5xx); any
|
|
205
|
+
* other refusal throws as it came. Sending the same batch again is safe: events are deduplicated by key.
|
|
206
|
+
*/
|
|
207
|
+
async sendUsage(events) {
|
|
208
|
+
try {
|
|
209
|
+
return await this.supervisor.authorized((token) => this.transport.sendUsageEvents(events, token));
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
if (error instanceof http_transport_1.HttpError && error.status < 500)
|
|
213
|
+
throw error;
|
|
214
|
+
throw new types_1.UsageDeliveryError(error instanceof Error ? error.message : 'Usage events could not be delivered');
|
|
215
|
+
}
|
|
216
|
+
}
|
|
147
217
|
/**
|
|
148
218
|
* Guard for write operations (fail-closed).
|
|
149
219
|
* Intercepts action if write operation is denied (e.g. disconnected).
|
|
@@ -245,7 +315,70 @@ class ShipRevClient {
|
|
|
245
315
|
return this.transport;
|
|
246
316
|
}
|
|
247
317
|
applyOnline(online) {
|
|
318
|
+
const changed = this.isOnline !== online;
|
|
248
319
|
this.isOnline = online;
|
|
320
|
+
if (changed) {
|
|
321
|
+
this.notifyLevels(this.mirror.organizationIds());
|
|
322
|
+
this.armExpiryTimer();
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
onMirrorChange(organizationIds) {
|
|
326
|
+
if (organizationIds === null) {
|
|
327
|
+
// The whole mirror was replaced: organizations that left it are forgotten.
|
|
328
|
+
for (const organizationId of [...this.reportedLevels.keys()]) {
|
|
329
|
+
if (!this.mirror.hasOrganization(organizationId))
|
|
330
|
+
this.reportedLevels.delete(organizationId);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
this.notifyLevels(organizationIds ?? this.mirror.organizationIds());
|
|
334
|
+
this.armExpiryTimer();
|
|
335
|
+
this.supervisor?.scheduleRenewals();
|
|
336
|
+
}
|
|
337
|
+
/** Reports every organization whose effective level differs from what was last reported. */
|
|
338
|
+
notifyLevels(organizationIds) {
|
|
339
|
+
const listener = this.options.on_level_change;
|
|
340
|
+
if (!listener)
|
|
341
|
+
return;
|
|
342
|
+
for (const organizationId of organizationIds) {
|
|
343
|
+
const level = this.effectiveLevel(organizationId);
|
|
344
|
+
if (!level) {
|
|
345
|
+
this.reportedLevels.delete(organizationId);
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
if ((0, degradation_1.sameLevel)(level, this.reportedLevels.get(organizationId)))
|
|
349
|
+
continue;
|
|
350
|
+
this.reportedLevels.set(organizationId, level);
|
|
351
|
+
try {
|
|
352
|
+
listener(organizationId, level);
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
// A listener failure never reaches the connection.
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/** While disconnected, wakes up when the earliest entry still valid expires, to report it. */
|
|
360
|
+
armExpiryTimer() {
|
|
361
|
+
if (this.expiryTimer) {
|
|
362
|
+
clearTimeout(this.expiryTimer);
|
|
363
|
+
this.expiryTimer = null;
|
|
364
|
+
}
|
|
365
|
+
if (!this.options.on_level_change || this.isOnline || !this.active)
|
|
366
|
+
return;
|
|
367
|
+
const now = Date.now();
|
|
368
|
+
let next = Number.POSITIVE_INFINITY;
|
|
369
|
+
for (const organizationId of this.mirror.organizationIds()) {
|
|
370
|
+
const validUntil = (0, degradation_1.validUntilOf)(this.mirror.getOrganization(organizationId));
|
|
371
|
+
if (validUntil !== undefined && validUntil > now)
|
|
372
|
+
next = Math.min(next, validUntil);
|
|
373
|
+
}
|
|
374
|
+
if (next === Number.POSITIVE_INFINITY)
|
|
375
|
+
return;
|
|
376
|
+
this.expiryTimer = setTimeout(() => {
|
|
377
|
+
this.expiryTimer = null;
|
|
378
|
+
this.notifyLevels(this.mirror.organizationIds());
|
|
379
|
+
this.armExpiryTimer();
|
|
380
|
+
}, next - now);
|
|
381
|
+
this.expiryTimer.unref();
|
|
249
382
|
}
|
|
250
383
|
learnExpectations(token) {
|
|
251
384
|
const expectations = (0, token_verifier_1.expectationsFromMachineToken)(token);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { DegradationLevel, EffectiveLevel, OrganizationSnapshot } from '../types';
|
|
2
|
+
/** The five levels in their strict order; each blocks what the one before it blocks, and more. */
|
|
3
|
+
export declare const DEGRADATION_LEVELS: readonly DegradationLevel[];
|
|
4
|
+
/** What a replica past its `valid_until` is tightened to, at least. */
|
|
5
|
+
export declare const EXPIRED_FLOOR: DegradationLevel;
|
|
6
|
+
/**
|
|
7
|
+
* The level an organization entry carries. Anything that is not one of the five values (missing, another
|
|
8
|
+
* string, not a string) is read as RESTRICT_USAGE: a level this client does not know is never read as looser.
|
|
9
|
+
*/
|
|
10
|
+
export declare function levelOf(entry: OrganizationSnapshot): DegradationLevel;
|
|
11
|
+
/** `valid_until` in epoch milliseconds, or undefined when missing or unparsable (read as already expired). */
|
|
12
|
+
export declare function validUntilOf(entry: OrganizationSnapshot): number | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* Combines an entry with what the client observes:
|
|
15
|
+
*
|
|
16
|
+
* - answered (online, or a pull of this organization just succeeded): the entry's level;
|
|
17
|
+
* - not answered and `now < valid_until`: the entry's level, marked degraded;
|
|
18
|
+
* - not answered and `now >= valid_until` (or no usable `valid_until`): at least RESTRICT_USAGE, marked expired.
|
|
19
|
+
*/
|
|
20
|
+
export declare function combineLevel(entry: OrganizationSnapshot, answered: boolean, now: number): EffectiveLevel;
|
|
21
|
+
/** True when two effective levels are the same triple. */
|
|
22
|
+
export declare function sameLevel(a: EffectiveLevel | undefined, b: EffectiveLevel | undefined): boolean;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EXPIRED_FLOOR = exports.DEGRADATION_LEVELS = void 0;
|
|
4
|
+
exports.levelOf = levelOf;
|
|
5
|
+
exports.validUntilOf = validUntilOf;
|
|
6
|
+
exports.combineLevel = combineLevel;
|
|
7
|
+
exports.sameLevel = sameLevel;
|
|
8
|
+
/** The five levels in their strict order; each blocks what the one before it blocks, and more. */
|
|
9
|
+
exports.DEGRADATION_LEVELS = [
|
|
10
|
+
'NONE',
|
|
11
|
+
'RESTRICT_NEW',
|
|
12
|
+
'RESTRICT_USAGE',
|
|
13
|
+
'RESTRICT_READ',
|
|
14
|
+
'SUSPENDED',
|
|
15
|
+
];
|
|
16
|
+
/** What a replica past its `valid_until` is tightened to, at least. */
|
|
17
|
+
exports.EXPIRED_FLOOR = 'RESTRICT_USAGE';
|
|
18
|
+
function rank(level) {
|
|
19
|
+
return exports.DEGRADATION_LEVELS.indexOf(level);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The level an organization entry carries. Anything that is not one of the five values (missing, another
|
|
23
|
+
* string, not a string) is read as RESTRICT_USAGE: a level this client does not know is never read as looser.
|
|
24
|
+
*/
|
|
25
|
+
function levelOf(entry) {
|
|
26
|
+
const raw = entry.degradation_level;
|
|
27
|
+
return typeof raw === 'string' && exports.DEGRADATION_LEVELS.includes(raw)
|
|
28
|
+
? raw
|
|
29
|
+
: exports.EXPIRED_FLOOR;
|
|
30
|
+
}
|
|
31
|
+
/** `valid_until` in epoch milliseconds, or undefined when missing or unparsable (read as already expired). */
|
|
32
|
+
function validUntilOf(entry) {
|
|
33
|
+
const raw = entry.valid_until;
|
|
34
|
+
if (typeof raw !== 'string')
|
|
35
|
+
return undefined;
|
|
36
|
+
const at = Date.parse(raw);
|
|
37
|
+
return Number.isFinite(at) ? at : undefined;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Combines an entry with what the client observes:
|
|
41
|
+
*
|
|
42
|
+
* - answered (online, or a pull of this organization just succeeded): the entry's level;
|
|
43
|
+
* - not answered and `now < valid_until`: the entry's level, marked degraded;
|
|
44
|
+
* - not answered and `now >= valid_until` (or no usable `valid_until`): at least RESTRICT_USAGE, marked expired.
|
|
45
|
+
*/
|
|
46
|
+
function combineLevel(entry, answered, now) {
|
|
47
|
+
const level = levelOf(entry);
|
|
48
|
+
if (answered) {
|
|
49
|
+
return { level, source: 'answer', expired: false };
|
|
50
|
+
}
|
|
51
|
+
const validUntil = validUntilOf(entry);
|
|
52
|
+
if (validUntil !== undefined && now < validUntil) {
|
|
53
|
+
return { level, source: 'degraded', expired: false };
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
level: rank(level) >= rank(exports.EXPIRED_FLOOR) ? level : exports.EXPIRED_FLOOR,
|
|
57
|
+
source: 'degraded',
|
|
58
|
+
expired: true,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** True when two effective levels are the same triple. */
|
|
62
|
+
function sameLevel(a, b) {
|
|
63
|
+
if (!a || !b)
|
|
64
|
+
return a === b;
|
|
65
|
+
return a.level === b.level && a.source === b.source && a.expired === b.expired;
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=degradation.js.map
|
|
@@ -1,14 +1,22 @@
|
|
|
1
|
-
import { Snapshot, SnapshotItem } from '../types';
|
|
1
|
+
import { OrganizationSnapshot, Snapshot, SnapshotItem } from '../types';
|
|
2
2
|
export declare const MAX_SUPPORTED_SCHEMA_VERSION = 1;
|
|
3
3
|
/**
|
|
4
4
|
* In-memory replica of the application-level entitlement snapshot served by
|
|
5
5
|
* `GET /sdk/v1/entitlements/snapshot`, indexed by organization and capability.
|
|
6
6
|
*/
|
|
7
7
|
export declare class EntitlementMirror {
|
|
8
|
+
private readonly onChange?;
|
|
8
9
|
private readonly organizations;
|
|
10
|
+
/** When each organization's entry was received (local clock). */
|
|
11
|
+
private readonly receivedAt;
|
|
9
12
|
private currentSchemaVersion;
|
|
10
13
|
private projectId;
|
|
11
14
|
private lastUpdatedAt;
|
|
15
|
+
/**
|
|
16
|
+
* @param onChange called after the mirror changed: with the organizations whose entry was replaced or
|
|
17
|
+
* removed, or with `null` when the whole mirror was replaced.
|
|
18
|
+
*/
|
|
19
|
+
constructor(onChange?: ((organizationIds: string[] | null) => void) | undefined);
|
|
12
20
|
/**
|
|
13
21
|
* Replaces the mirror with an application-level snapshot envelope.
|
|
14
22
|
* If schema_version is higher than supported, the update is rejected and the existing mirror is retained.
|
|
@@ -23,6 +31,12 @@ export declare class EntitlementMirror {
|
|
|
23
31
|
* Removes an organization, for a refill whose envelope no longer holds it (unsubscribed or deleted).
|
|
24
32
|
*/
|
|
25
33
|
removeOrganization(organizationId: string): void;
|
|
34
|
+
/** The entry of one organization, or `undefined` when the mirror does not hold it. */
|
|
35
|
+
getOrganization(organizationId: string): OrganizationSnapshot | undefined;
|
|
36
|
+
/** When the entry of one organization was received (local clock), or `undefined`. */
|
|
37
|
+
getReceivedAt(organizationId: string): number | undefined;
|
|
38
|
+
/** The organizations the mirror holds. */
|
|
39
|
+
organizationIds(): string[];
|
|
26
40
|
/**
|
|
27
41
|
* Revision of one organization, or `undefined` when the mirror does not hold it.
|
|
28
42
|
*/
|
|
@@ -7,10 +7,20 @@ exports.MAX_SUPPORTED_SCHEMA_VERSION = 1;
|
|
|
7
7
|
* `GET /sdk/v1/entitlements/snapshot`, indexed by organization and capability.
|
|
8
8
|
*/
|
|
9
9
|
class EntitlementMirror {
|
|
10
|
+
onChange;
|
|
10
11
|
organizations = new Map();
|
|
12
|
+
/** When each organization's entry was received (local clock). */
|
|
13
|
+
receivedAt = new Map();
|
|
11
14
|
currentSchemaVersion = exports.MAX_SUPPORTED_SCHEMA_VERSION;
|
|
12
15
|
projectId = '';
|
|
13
16
|
lastUpdatedAt = 0;
|
|
17
|
+
/**
|
|
18
|
+
* @param onChange called after the mirror changed: with the organizations whose entry was replaced or
|
|
19
|
+
* removed, or with `null` when the whole mirror was replaced.
|
|
20
|
+
*/
|
|
21
|
+
constructor(onChange) {
|
|
22
|
+
this.onChange = onChange;
|
|
23
|
+
}
|
|
14
24
|
/**
|
|
15
25
|
* Replaces the mirror with an application-level snapshot envelope.
|
|
16
26
|
* If schema_version is higher than supported, the update is rejected and the existing mirror is retained.
|
|
@@ -19,13 +29,17 @@ class EntitlementMirror {
|
|
|
19
29
|
if (!this.acceptsEnvelope(snapshot)) {
|
|
20
30
|
return false;
|
|
21
31
|
}
|
|
32
|
+
const now = Date.now();
|
|
22
33
|
this.organizations.clear();
|
|
34
|
+
this.receivedAt.clear();
|
|
23
35
|
this.projectId = snapshot.project_id;
|
|
24
36
|
this.currentSchemaVersion = snapshot.schema_version;
|
|
25
37
|
for (const [organizationId, organization] of Object.entries(snapshot.organizations ?? {})) {
|
|
26
38
|
this.organizations.set(organizationId, organization);
|
|
39
|
+
this.receivedAt.set(organizationId, now);
|
|
27
40
|
}
|
|
28
|
-
this.lastUpdatedAt =
|
|
41
|
+
this.lastUpdatedAt = now;
|
|
42
|
+
this.onChange?.(null);
|
|
29
43
|
return true;
|
|
30
44
|
}
|
|
31
45
|
/**
|
|
@@ -39,14 +53,20 @@ class EntitlementMirror {
|
|
|
39
53
|
if (this.projectId && snapshot.project_id !== this.projectId) {
|
|
40
54
|
return false;
|
|
41
55
|
}
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
const changed = [];
|
|
42
58
|
this.projectId = snapshot.project_id;
|
|
43
59
|
for (const [organizationId, organization] of Object.entries(snapshot.organizations ?? {})) {
|
|
44
60
|
const known = this.organizations.get(organizationId);
|
|
45
61
|
if (!known || organization.revision >= known.revision) {
|
|
46
62
|
this.organizations.set(organizationId, organization);
|
|
63
|
+
this.receivedAt.set(organizationId, now);
|
|
64
|
+
changed.push(organizationId);
|
|
47
65
|
}
|
|
48
66
|
}
|
|
49
|
-
this.lastUpdatedAt =
|
|
67
|
+
this.lastUpdatedAt = now;
|
|
68
|
+
if (changed.length > 0)
|
|
69
|
+
this.onChange?.(changed);
|
|
50
70
|
return true;
|
|
51
71
|
}
|
|
52
72
|
/**
|
|
@@ -54,9 +74,23 @@ class EntitlementMirror {
|
|
|
54
74
|
*/
|
|
55
75
|
removeOrganization(organizationId) {
|
|
56
76
|
if (this.organizations.delete(organizationId)) {
|
|
77
|
+
this.receivedAt.delete(organizationId);
|
|
57
78
|
this.lastUpdatedAt = Date.now();
|
|
79
|
+
this.onChange?.([organizationId]);
|
|
58
80
|
}
|
|
59
81
|
}
|
|
82
|
+
/** The entry of one organization, or `undefined` when the mirror does not hold it. */
|
|
83
|
+
getOrganization(organizationId) {
|
|
84
|
+
return this.organizations.get(organizationId);
|
|
85
|
+
}
|
|
86
|
+
/** When the entry of one organization was received (local clock), or `undefined`. */
|
|
87
|
+
getReceivedAt(organizationId) {
|
|
88
|
+
return this.receivedAt.get(organizationId);
|
|
89
|
+
}
|
|
90
|
+
/** The organizations the mirror holds. */
|
|
91
|
+
organizationIds() {
|
|
92
|
+
return [...this.organizations.keys()];
|
|
93
|
+
}
|
|
60
94
|
/**
|
|
61
95
|
* Revision of one organization, or `undefined` when the mirror does not hold it.
|
|
62
96
|
*/
|
|
@@ -86,17 +86,9 @@ class Adjudicator {
|
|
|
86
86
|
adjudicated_at: now,
|
|
87
87
|
};
|
|
88
88
|
}
|
|
89
|
-
// Beyond the remaining allowance
|
|
90
|
-
//
|
|
91
|
-
|
|
92
|
-
return {
|
|
93
|
-
allowed: true,
|
|
94
|
-
remaining: 0,
|
|
95
|
-
limit,
|
|
96
|
-
source: 'realtime',
|
|
97
|
-
adjudicated_at: now,
|
|
98
|
-
};
|
|
99
|
-
}
|
|
89
|
+
// Beyond the remaining allowance the call is not decided here, whatever the policy: whether credits (and, for
|
|
90
|
+
// ALLOW_AND_BILL, an overdraft) cover it is state the mirror does not hold. The local answer is a refusal;
|
|
91
|
+
// adjudicateAsync() asks the service on it, and without an answer the call stays refused (fail closed).
|
|
100
92
|
return {
|
|
101
93
|
allowed: false,
|
|
102
94
|
remaining: (0, decimal_1.decimalToNumber)(item.remaining),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AdjudicationLookupRequest, AdjudicationLookupResponse, ConfirmReservationResult, JwksResponse, ReleaseReservationResult, ReservationResult, ReserveOptions, Snapshot, UsageEventItem, UsageEventsResponse } from '../types';
|
|
1
|
+
import { AdjudicationLookupRequest, AdjudicationLookupResponse, ConfirmReservationResult, JwksResponse, ReleaseReservationResult, ReservationResult, ReserveOptions, Snapshot, UsageEventItem, UsageEventsResponse, UsageSendEvent, UsageSendResult } from '../types';
|
|
2
2
|
/** A non-success HTTP answer from the instance; `status` lets callers tell a refused token from an outage. */
|
|
3
3
|
export declare class HttpError extends Error {
|
|
4
4
|
readonly status: number;
|
|
@@ -37,6 +37,11 @@ export declare class HttpTransport {
|
|
|
37
37
|
* Quantities are sent as decimal strings; `properties` travel as the event's `dimensions`.
|
|
38
38
|
*/
|
|
39
39
|
reportUsageEvents(events: UsageEventItem[], token: string): Promise<UsageEventsResponse>;
|
|
40
|
+
/**
|
|
41
|
+
* Sends a batch of usage events as they are: POST /sdk/v1/usage-events. A string quantity travels unchanged,
|
|
42
|
+
* so decimals keep every digit.
|
|
43
|
+
*/
|
|
44
|
+
sendUsageEvents(events: UsageSendEvent[], token: string): Promise<UsageSendResult>;
|
|
40
45
|
/**
|
|
41
46
|
* Authoritative ruling when the mirror misses an organization or capability: POST /sdk/v1/adjudicate.
|
|
42
47
|
*/
|
|
@@ -97,6 +97,26 @@ class HttpTransport {
|
|
|
97
97
|
rejected: body.rejected ?? [],
|
|
98
98
|
};
|
|
99
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* Sends a batch of usage events as they are: POST /sdk/v1/usage-events. A string quantity travels unchanged,
|
|
102
|
+
* so decimals keep every digit.
|
|
103
|
+
*/
|
|
104
|
+
async sendUsageEvents(events, token) {
|
|
105
|
+
const wireEvents = events.map((event) => ({
|
|
106
|
+
usage_event_id: event.usage_event_id,
|
|
107
|
+
organization_id: event.organization_id,
|
|
108
|
+
capability_key: event.capability_key,
|
|
109
|
+
quantity: typeof event.quantity === 'string' ? event.quantity.trim() : (0, decimal_1.toDecimalString)(event.quantity),
|
|
110
|
+
occurred_at: event.occurred_at,
|
|
111
|
+
...(event.properties !== undefined ? { dimensions: event.properties } : {}),
|
|
112
|
+
}));
|
|
113
|
+
const body = await this.postJson('/sdk/v1/usage-events', { events: wireEvents }, token, 'Failed to send usage events');
|
|
114
|
+
return {
|
|
115
|
+
accepted_count: body.accepted_count,
|
|
116
|
+
duplicates_dropped: body.duplicates_dropped,
|
|
117
|
+
rejected: body.rejected ?? [],
|
|
118
|
+
};
|
|
119
|
+
}
|
|
100
120
|
/**
|
|
101
121
|
* Authoritative ruling when the mirror misses an organization or capability: POST /sdk/v1/adjudicate.
|
|
102
122
|
*/
|
|
@@ -129,7 +149,7 @@ class HttpTransport {
|
|
|
129
149
|
const body = await this.postJson('/sdk/v1/reservations/reserve', wireRequest, token, 'Reservation failed');
|
|
130
150
|
return {
|
|
131
151
|
reservation_id: body.reservation_id,
|
|
132
|
-
status: body.status
|
|
152
|
+
status: body.status,
|
|
133
153
|
expires_at: body.expires_at,
|
|
134
154
|
};
|
|
135
155
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -50,7 +50,54 @@ export interface SnapshotItem {
|
|
|
50
50
|
export interface OrganizationSnapshot {
|
|
51
51
|
revision: number;
|
|
52
52
|
wallet_balance: string;
|
|
53
|
+
/**
|
|
54
|
+
* Credits the wallet may go below zero by for ALLOW_AND_BILL capabilities. Informational: the mirror never widens
|
|
55
|
+
* a local ruling with it; beyond the allowance the service decides. Absent on instances that predate it.
|
|
56
|
+
*/
|
|
57
|
+
overdraft_limit?: string;
|
|
53
58
|
items: Record<string, SnapshotItem>;
|
|
59
|
+
/**
|
|
60
|
+
* Degradation level the instance computed for the organization. Instances that predate it leave it out; a
|
|
61
|
+
* value outside `DegradationLevel` is read as `RESTRICT_USAGE`.
|
|
62
|
+
*/
|
|
63
|
+
degradation_level?: string;
|
|
64
|
+
/** ISO 8601 time until which this entry may be used without a newer answer. */
|
|
65
|
+
valid_until?: string;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Degradation level of a buyer organization, strictly increasing: `RESTRICT_NEW` blocks new commercial objects,
|
|
69
|
+
* `RESTRICT_USAGE` every write, `RESTRICT_READ` end-user reads too, and `SUSPENDED` is an explicit "no
|
|
70
|
+
* entitlement". Computed by the instance; a client only enforces it.
|
|
71
|
+
*/
|
|
72
|
+
export type DegradationLevel = 'NONE' | 'RESTRICT_NEW' | 'RESTRICT_USAGE' | 'RESTRICT_READ' | 'SUSPENDED';
|
|
73
|
+
/**
|
|
74
|
+
* The level to act on for one organization, combined from the mirror entry and what the client observes:
|
|
75
|
+
* `source: 'answer'` while the instance answers (online, or a pull of the organization just succeeded);
|
|
76
|
+
* `'degraded'` when acting on the mirror without an answer, with `expired` once the entry's `valid_until` has
|
|
77
|
+
* passed (the level is then at least `RESTRICT_USAGE`).
|
|
78
|
+
*/
|
|
79
|
+
export interface EffectiveLevel {
|
|
80
|
+
level: DegradationLevel;
|
|
81
|
+
source: 'answer' | 'degraded';
|
|
82
|
+
expired: boolean;
|
|
83
|
+
}
|
|
84
|
+
/** One usage event for `sendUsage()`. The quantity may be a decimal string, sent as it is. */
|
|
85
|
+
export interface UsageSendEvent {
|
|
86
|
+
usage_event_id: string;
|
|
87
|
+
organization_id: string;
|
|
88
|
+
capability_key: string;
|
|
89
|
+
quantity: number | string;
|
|
90
|
+
occurred_at: string;
|
|
91
|
+
properties?: Record<string, unknown>;
|
|
92
|
+
}
|
|
93
|
+
/** What the instance did with a batch sent by `sendUsage()`. */
|
|
94
|
+
export interface UsageSendResult {
|
|
95
|
+
accepted_count: number;
|
|
96
|
+
duplicates_dropped: number;
|
|
97
|
+
rejected: Array<{
|
|
98
|
+
usage_event_id: string;
|
|
99
|
+
reason: string;
|
|
100
|
+
}>;
|
|
54
101
|
}
|
|
55
102
|
/**
|
|
56
103
|
* Application-level entitlement snapshot envelope served by `GET /sdk/v1/entitlements/snapshot`:
|
|
@@ -117,7 +164,7 @@ export interface ReserveOptions {
|
|
|
117
164
|
}
|
|
118
165
|
export interface ReservationResult {
|
|
119
166
|
reservation_id: string;
|
|
120
|
-
status: '
|
|
167
|
+
status: 'RESERVED' | 'CONFIRMED' | 'RELEASED';
|
|
121
168
|
expires_at: string;
|
|
122
169
|
}
|
|
123
170
|
export interface ConfirmReservationResult {
|
|
@@ -150,11 +197,25 @@ export interface ShipRevClientOptions {
|
|
|
150
197
|
backlog?: BacklogConfig;
|
|
151
198
|
on_flush_failure?: (events: UsageEventItem[], error: Error) => void;
|
|
152
199
|
on_rejected?: (rejected: RejectedEvent[]) => void;
|
|
200
|
+
/**
|
|
201
|
+
* Called when the effective level of an organization changes: a new entry, the connection going up or down,
|
|
202
|
+
* or an entry's `valid_until` passing while disconnected. Never called for an organization the mirror does
|
|
203
|
+
* not hold.
|
|
204
|
+
*/
|
|
205
|
+
on_level_change?: (organization_id: string, level: EffectiveLevel) => void;
|
|
153
206
|
}
|
|
154
207
|
export declare class DisconnectedWriteError extends Error {
|
|
155
208
|
readonly reason = "disconnected_write";
|
|
156
209
|
constructor(message?: string);
|
|
157
210
|
}
|
|
211
|
+
/**
|
|
212
|
+
* Thrown by `sendUsage()` when the batch did not reach the instance or the instance failed to process it (a
|
|
213
|
+
* network error, a timeout or a 5xx answer). Nothing in the batch can be assumed delivered; sending it again is
|
|
214
|
+
* safe, as every event carries its idempotency key.
|
|
215
|
+
*/
|
|
216
|
+
export declare class UsageDeliveryError extends Error {
|
|
217
|
+
constructor(message?: string);
|
|
218
|
+
}
|
|
158
219
|
/** Why `verifyToken()` refused a correctly signed, unexpired token. */
|
|
159
220
|
export type TokenRejectionReason =
|
|
160
221
|
/** The client has not obtained a machine token yet, so the expected issuer and application are unknown. */
|
package/dist/types.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.TokenRejectedError = exports.DisconnectedWriteError = void 0;
|
|
3
|
+
exports.TokenRejectedError = exports.UsageDeliveryError = exports.DisconnectedWriteError = void 0;
|
|
4
4
|
class DisconnectedWriteError extends Error {
|
|
5
5
|
reason = 'disconnected_write';
|
|
6
6
|
constructor(message = 'Write operation denied while client is disconnected') {
|
|
@@ -9,6 +9,18 @@ class DisconnectedWriteError extends Error {
|
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
11
|
exports.DisconnectedWriteError = DisconnectedWriteError;
|
|
12
|
+
/**
|
|
13
|
+
* Thrown by `sendUsage()` when the batch did not reach the instance or the instance failed to process it (a
|
|
14
|
+
* network error, a timeout or a 5xx answer). Nothing in the batch can be assumed delivered; sending it again is
|
|
15
|
+
* safe, as every event carries its idempotency key.
|
|
16
|
+
*/
|
|
17
|
+
class UsageDeliveryError extends Error {
|
|
18
|
+
constructor(message = 'Usage events could not be delivered') {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = 'UsageDeliveryError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.UsageDeliveryError = UsageDeliveryError;
|
|
12
24
|
/**
|
|
13
25
|
* Thrown by `verifyToken()` when a token is correctly signed but is not a session token this client
|
|
14
26
|
* accepts. The message names the reason and never contains the token.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shiprev/server-sdk-node",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.1",
|
|
4
4
|
"description": "Server SDK for Node.js and NestJS services: token verification, local entitlement rulings, usage reporting, and two-phase reservations against a ShipRev instance.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"shiprev",
|
|
@@ -42,15 +42,6 @@
|
|
|
42
42
|
"access": "public",
|
|
43
43
|
"tag": "beta"
|
|
44
44
|
},
|
|
45
|
-
"scripts": {
|
|
46
|
-
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
47
|
-
"build": "tsc -p tsconfig.build.json",
|
|
48
|
-
"prepack": "pnpm run clean && pnpm run build",
|
|
49
|
-
"test": "jest",
|
|
50
|
-
"test:nest9": "node scripts/test-nest9.mjs",
|
|
51
|
-
"lint": "eslint \"src/**/*.ts\"",
|
|
52
|
-
"format": "prettier --write \"src/**/*.ts\""
|
|
53
|
-
},
|
|
54
45
|
"peerDependencies": {
|
|
55
46
|
"@nestjs/common": "^9.0.0 || ^10.0.0 || ^11.0.0",
|
|
56
47
|
"@nestjs/core": "^9.0.0 || ^10.0.0 || ^11.0.0",
|
|
@@ -96,5 +87,13 @@
|
|
|
96
87
|
"^.+\\.ts$": "ts-jest"
|
|
97
88
|
},
|
|
98
89
|
"testEnvironment": "node"
|
|
90
|
+
},
|
|
91
|
+
"scripts": {
|
|
92
|
+
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
93
|
+
"build": "tsc -p tsconfig.build.json",
|
|
94
|
+
"test": "jest",
|
|
95
|
+
"test:nest9": "node scripts/test-nest9.mjs",
|
|
96
|
+
"lint": "eslint \"src/**/*.ts\"",
|
|
97
|
+
"format": "prettier --write \"src/**/*.ts\""
|
|
99
98
|
}
|
|
100
|
-
}
|
|
99
|
+
}
|