@canarygate/sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +97 -0
- package/dist/canary-gate-base-D069Q1Z_.d.mts +65 -0
- package/dist/canary-gate-base-D069Q1Z_.d.ts +65 -0
- package/dist/chunk-7KAJ7OJO.mjs +313 -0
- package/dist/client.d.mts +7 -0
- package/dist/client.d.ts +7 -0
- package/dist/client.js +360 -0
- package/dist/client.mjs +27 -0
- package/dist/server.d.mts +7 -0
- package/dist/server.d.ts +7 -0
- package/dist/server.js +346 -0
- package/dist/server.mjs +13 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CanaryGate
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# @canarygate/sdk
|
|
2
|
+
|
|
3
|
+
Feature flag client for [CanaryGate](https://github.com/rborges98/canarygate).
|
|
4
|
+
|
|
5
|
+
- **Server (Node.js)** — snapshot on `init()` + live updates via SSE, with auto-reconnect and heartbeat detection
|
|
6
|
+
- **Browser** — flags fetched once and cached; SSE stays off to protect your infrastructure
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install @canarygate/sdk
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Quick start
|
|
15
|
+
|
|
16
|
+
### Server — real-time
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { CanaryGate } from '@canarygate/sdk/server'
|
|
20
|
+
|
|
21
|
+
const gate = new CanaryGate('your-api-key', {
|
|
22
|
+
environment: 'production',
|
|
23
|
+
stream: true
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
await gate.init()
|
|
27
|
+
// flags keep updating in the background via SSE
|
|
28
|
+
|
|
29
|
+
gate.disconnect() // when shutting down
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Browser — cached
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { CanaryGate } from '@canarygate/sdk/client'
|
|
36
|
+
|
|
37
|
+
const gate = new CanaryGate('your-api-key', {
|
|
38
|
+
environment: 'production'
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
await gate.init()
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Evaluating flags
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
const flag = gate.getFlag('new-checkout', { userId: 'user-123' })
|
|
48
|
+
|
|
49
|
+
if (flag?.enabled) {
|
|
50
|
+
// boolean flag is on,
|
|
51
|
+
// or user-123 falls inside the rollout percentage
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const allFlags = gate.getFlags({ userId: 'user-123' })
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Evaluations return a `FlagData`:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
type FlagData =
|
|
61
|
+
| { key: string; type: 'boolean'; enabled: boolean }
|
|
62
|
+
| { key: string; type: 'rollout'; enabled: boolean; percent: number }
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Rollout evaluation hashes `userId` deterministically — the same user always gets the same result for the same percentage.
|
|
66
|
+
|
|
67
|
+
## Options
|
|
68
|
+
|
|
69
|
+
| Option | Type | Default | Description |
|
|
70
|
+
| -------------------- | --------- | ----------------------- | ------------------------------------------------ |
|
|
71
|
+
| `baseUrl` | `string` | `http://localhost:3001` | CanaryGate API base URL |
|
|
72
|
+
| `environment` | `string` | — | Environment to evaluate flags against |
|
|
73
|
+
| `stream` | `boolean` | `false` | Real-time SSE updates (server mode only) |
|
|
74
|
+
| `reconnectDelay` | `number` | `5000` | Initial SSE reconnect delay (ms) |
|
|
75
|
+
| `maxReconnectDelay` | `number` | `30000` | Reconnect delay cap, exponential backoff (ms) |
|
|
76
|
+
| `heartbeatTimeoutMs` | `number` | `65000` | Silence window before treating the stream as dead |
|
|
77
|
+
|
|
78
|
+
## Methods
|
|
79
|
+
|
|
80
|
+
| Method | Description |
|
|
81
|
+
| --------------------- | -------------------------------------------------- |
|
|
82
|
+
| `init()` | Fetches flags and starts the stream when enabled |
|
|
83
|
+
| `getFlag(key, ctx?)` | Evaluates one flag (`boolean` or `rollout`) |
|
|
84
|
+
| `getFlags(ctx?)` | Evaluates all cached flags |
|
|
85
|
+
| `isStale()` | Whether the last sync attempt failed |
|
|
86
|
+
| `getLastSyncAt()` | Timestamp of the last successful sync |
|
|
87
|
+
| `disconnect()` | Stops the stream and clears timers |
|
|
88
|
+
|
|
89
|
+
## How sync works
|
|
90
|
+
|
|
91
|
+
1. `init()` fetches a full snapshot from `/sdk/flags`.
|
|
92
|
+
2. With `stream: true`, an SSE connection receives granular updates per change.
|
|
93
|
+
3. On disconnect, the SDK reconnects with exponential backoff and does a full resync over the snapshot endpoint.
|
|
94
|
+
|
|
95
|
+
## License
|
|
96
|
+
|
|
97
|
+
[MIT](./LICENSE)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
type BooleanFlagData = {
|
|
2
|
+
key: string;
|
|
3
|
+
type: 'boolean';
|
|
4
|
+
enabled: boolean;
|
|
5
|
+
};
|
|
6
|
+
type RolloutFlagData = {
|
|
7
|
+
key: string;
|
|
8
|
+
type: 'rollout';
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
percent: number;
|
|
11
|
+
};
|
|
12
|
+
type FlagData = BooleanFlagData | RolloutFlagData;
|
|
13
|
+
type FlagEvaluationContext = {
|
|
14
|
+
userId?: string;
|
|
15
|
+
};
|
|
16
|
+
type CanaryGateOptions = {
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
environment?: string;
|
|
19
|
+
stream?: boolean;
|
|
20
|
+
reconnectDelay?: number;
|
|
21
|
+
maxReconnectDelay?: number;
|
|
22
|
+
heartbeatTimeoutMs?: number;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
declare class CanaryGateBase {
|
|
26
|
+
protected readonly apiKey: string;
|
|
27
|
+
protected readonly streamEnabled: boolean;
|
|
28
|
+
protected readonly anonIdFactory: () => string;
|
|
29
|
+
private readonly baseUrl;
|
|
30
|
+
private readonly environment;
|
|
31
|
+
private readonly reconnectDelay;
|
|
32
|
+
private readonly maxReconnectDelay;
|
|
33
|
+
private readonly heartbeatTimeoutMs;
|
|
34
|
+
private cache;
|
|
35
|
+
private cacheVersions;
|
|
36
|
+
private readonly anonId;
|
|
37
|
+
private streamAbortController;
|
|
38
|
+
private reconnectTimeout;
|
|
39
|
+
private heartbeatTimeout;
|
|
40
|
+
private streamRetryDelay;
|
|
41
|
+
private reconnectAttempts;
|
|
42
|
+
private stale;
|
|
43
|
+
private lastSyncAt;
|
|
44
|
+
private destroyed;
|
|
45
|
+
constructor(apiKey: string, options: CanaryGateOptions | undefined, streamEnabled: boolean, anonIdFactory: () => string);
|
|
46
|
+
protected warnStreamDisabled(): void;
|
|
47
|
+
init(): Promise<void>;
|
|
48
|
+
private replaceCacheFromSnapshot;
|
|
49
|
+
private fetchFlags;
|
|
50
|
+
private applyFlagUpdate;
|
|
51
|
+
private applyFlagDeletion;
|
|
52
|
+
private handleStreamMessage;
|
|
53
|
+
private clearHeartbeatTimeout;
|
|
54
|
+
private bumpHeartbeatTimeout;
|
|
55
|
+
private scheduleReconnect;
|
|
56
|
+
private consumeStream;
|
|
57
|
+
private connectStream;
|
|
58
|
+
getFlag(key: string, context?: FlagEvaluationContext): FlagData | undefined;
|
|
59
|
+
getFlags(context?: FlagEvaluationContext): FlagData[];
|
|
60
|
+
isStale(): boolean;
|
|
61
|
+
getLastSyncAt(): string | null;
|
|
62
|
+
disconnect(): void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export { CanaryGateBase as C, type CanaryGateOptions as a };
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
type BooleanFlagData = {
|
|
2
|
+
key: string;
|
|
3
|
+
type: 'boolean';
|
|
4
|
+
enabled: boolean;
|
|
5
|
+
};
|
|
6
|
+
type RolloutFlagData = {
|
|
7
|
+
key: string;
|
|
8
|
+
type: 'rollout';
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
percent: number;
|
|
11
|
+
};
|
|
12
|
+
type FlagData = BooleanFlagData | RolloutFlagData;
|
|
13
|
+
type FlagEvaluationContext = {
|
|
14
|
+
userId?: string;
|
|
15
|
+
};
|
|
16
|
+
type CanaryGateOptions = {
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
environment?: string;
|
|
19
|
+
stream?: boolean;
|
|
20
|
+
reconnectDelay?: number;
|
|
21
|
+
maxReconnectDelay?: number;
|
|
22
|
+
heartbeatTimeoutMs?: number;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
declare class CanaryGateBase {
|
|
26
|
+
protected readonly apiKey: string;
|
|
27
|
+
protected readonly streamEnabled: boolean;
|
|
28
|
+
protected readonly anonIdFactory: () => string;
|
|
29
|
+
private readonly baseUrl;
|
|
30
|
+
private readonly environment;
|
|
31
|
+
private readonly reconnectDelay;
|
|
32
|
+
private readonly maxReconnectDelay;
|
|
33
|
+
private readonly heartbeatTimeoutMs;
|
|
34
|
+
private cache;
|
|
35
|
+
private cacheVersions;
|
|
36
|
+
private readonly anonId;
|
|
37
|
+
private streamAbortController;
|
|
38
|
+
private reconnectTimeout;
|
|
39
|
+
private heartbeatTimeout;
|
|
40
|
+
private streamRetryDelay;
|
|
41
|
+
private reconnectAttempts;
|
|
42
|
+
private stale;
|
|
43
|
+
private lastSyncAt;
|
|
44
|
+
private destroyed;
|
|
45
|
+
constructor(apiKey: string, options: CanaryGateOptions | undefined, streamEnabled: boolean, anonIdFactory: () => string);
|
|
46
|
+
protected warnStreamDisabled(): void;
|
|
47
|
+
init(): Promise<void>;
|
|
48
|
+
private replaceCacheFromSnapshot;
|
|
49
|
+
private fetchFlags;
|
|
50
|
+
private applyFlagUpdate;
|
|
51
|
+
private applyFlagDeletion;
|
|
52
|
+
private handleStreamMessage;
|
|
53
|
+
private clearHeartbeatTimeout;
|
|
54
|
+
private bumpHeartbeatTimeout;
|
|
55
|
+
private scheduleReconnect;
|
|
56
|
+
private consumeStream;
|
|
57
|
+
private connectStream;
|
|
58
|
+
getFlag(key: string, context?: FlagEvaluationContext): FlagData | undefined;
|
|
59
|
+
getFlags(context?: FlagEvaluationContext): FlagData[];
|
|
60
|
+
isStale(): boolean;
|
|
61
|
+
getLastSyncAt(): string | null;
|
|
62
|
+
disconnect(): void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export { CanaryGateBase as C, type CanaryGateOptions as a };
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// src/hash.ts
|
|
2
|
+
function hashString(input) {
|
|
3
|
+
let hash = 5381;
|
|
4
|
+
for (let i = 0; i < input.length; i++) {
|
|
5
|
+
hash = (hash << 5) + hash ^ input.charCodeAt(i);
|
|
6
|
+
hash = hash >>> 0;
|
|
7
|
+
}
|
|
8
|
+
return hash % 100;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// src/sse.ts
|
|
12
|
+
function parseSseEventBlock(block) {
|
|
13
|
+
let event = "message";
|
|
14
|
+
const dataLines = [];
|
|
15
|
+
let retryMs;
|
|
16
|
+
for (const line of block.split(/\r?\n/)) {
|
|
17
|
+
if (!line || line.startsWith(":")) continue;
|
|
18
|
+
const separatorIndex = line.indexOf(":");
|
|
19
|
+
const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);
|
|
20
|
+
const value = separatorIndex === -1 ? "" : line.slice(separatorIndex + 1).trimStart();
|
|
21
|
+
if (field === "event") {
|
|
22
|
+
event = value || "message";
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (field === "data") {
|
|
26
|
+
dataLines.push(value);
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (field === "retry") {
|
|
30
|
+
const parsedRetryMs = Number.parseInt(value, 10);
|
|
31
|
+
if (Number.isFinite(parsedRetryMs) && parsedRetryMs > 0) {
|
|
32
|
+
retryMs = parsedRetryMs;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (dataLines.length === 0 && retryMs === void 0) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
return { event, data: dataLines.join("\n"), retryMs };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/canary-gate-base.ts
|
|
43
|
+
var DEFAULT_MAX_RECONNECT_DELAY_MS = 3e4;
|
|
44
|
+
var DEFAULT_HEARTBEAT_TIMEOUT_MS = 65e3;
|
|
45
|
+
function isAbortError(error) {
|
|
46
|
+
return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError";
|
|
47
|
+
}
|
|
48
|
+
function parseTimestamp(value) {
|
|
49
|
+
const parsed = Date.parse(value);
|
|
50
|
+
return Number.isNaN(parsed) ? 0 : parsed;
|
|
51
|
+
}
|
|
52
|
+
var CanaryGateBase = class {
|
|
53
|
+
constructor(apiKey, options = {}, streamEnabled, anonIdFactory) {
|
|
54
|
+
this.apiKey = apiKey;
|
|
55
|
+
this.streamEnabled = streamEnabled;
|
|
56
|
+
this.anonIdFactory = anonIdFactory;
|
|
57
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
58
|
+
this.cacheVersions = /* @__PURE__ */ new Map();
|
|
59
|
+
this.streamAbortController = null;
|
|
60
|
+
this.reconnectTimeout = null;
|
|
61
|
+
this.heartbeatTimeout = null;
|
|
62
|
+
this.reconnectAttempts = 0;
|
|
63
|
+
this.stale = false;
|
|
64
|
+
this.lastSyncAt = null;
|
|
65
|
+
this.destroyed = false;
|
|
66
|
+
this.baseUrl = (options.baseUrl ?? "http://localhost:3001").replace(
|
|
67
|
+
/\/$/,
|
|
68
|
+
""
|
|
69
|
+
);
|
|
70
|
+
this.environment = options.environment;
|
|
71
|
+
this.reconnectDelay = options.reconnectDelay ?? 5e3;
|
|
72
|
+
this.maxReconnectDelay = Math.max(
|
|
73
|
+
options.maxReconnectDelay ?? DEFAULT_MAX_RECONNECT_DELAY_MS,
|
|
74
|
+
this.reconnectDelay
|
|
75
|
+
);
|
|
76
|
+
this.heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? DEFAULT_HEARTBEAT_TIMEOUT_MS;
|
|
77
|
+
this.streamRetryDelay = this.reconnectDelay;
|
|
78
|
+
this.anonId = anonIdFactory();
|
|
79
|
+
}
|
|
80
|
+
warnStreamDisabled() {
|
|
81
|
+
console.warn(
|
|
82
|
+
"[canarygate] Real-time streams (SSE) are disabled in browser environments to protect network architecture."
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
async init() {
|
|
86
|
+
await this.fetchFlags();
|
|
87
|
+
if (this.streamEnabled) this.connectStream();
|
|
88
|
+
}
|
|
89
|
+
replaceCacheFromSnapshot(flags, requestedAt) {
|
|
90
|
+
const nextCache = /* @__PURE__ */ new Map();
|
|
91
|
+
const nextVersions = /* @__PURE__ */ new Map();
|
|
92
|
+
for (const flag of flags) {
|
|
93
|
+
const nextVersion = parseTimestamp(flag.updatedAt);
|
|
94
|
+
const currentVersion = this.cacheVersions.get(flag.key) ?? -1;
|
|
95
|
+
if (currentVersion > nextVersion && currentVersion > requestedAt) {
|
|
96
|
+
const currentFlag = this.cache.get(flag.key);
|
|
97
|
+
if (currentFlag) nextCache.set(flag.key, currentFlag);
|
|
98
|
+
nextVersions.set(flag.key, currentVersion);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
nextCache.set(flag.key, flag);
|
|
102
|
+
nextVersions.set(flag.key, nextVersion);
|
|
103
|
+
}
|
|
104
|
+
for (const [key, currentVersion] of this.cacheVersions) {
|
|
105
|
+
if (nextVersions.has(key) || currentVersion <= requestedAt) {
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const currentFlag = this.cache.get(key);
|
|
109
|
+
if (currentFlag) nextCache.set(key, currentFlag);
|
|
110
|
+
nextVersions.set(key, currentVersion);
|
|
111
|
+
}
|
|
112
|
+
this.cache = nextCache;
|
|
113
|
+
this.cacheVersions = nextVersions;
|
|
114
|
+
this.stale = false;
|
|
115
|
+
this.lastSyncAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
116
|
+
}
|
|
117
|
+
async fetchFlags() {
|
|
118
|
+
const requestedAt = Date.now();
|
|
119
|
+
try {
|
|
120
|
+
const headers = { "X-Api-Key": this.apiKey };
|
|
121
|
+
if (this.environment) headers["X-Environment"] = this.environment;
|
|
122
|
+
const res = await fetch(`${this.baseUrl}/sdk/flags`, { headers });
|
|
123
|
+
if (!res.ok) {
|
|
124
|
+
console.error(
|
|
125
|
+
`[canarygate] Failed to fetch flags: ${res.status} ${res.statusText}`
|
|
126
|
+
);
|
|
127
|
+
this.stale = true;
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
const body = await res.json();
|
|
131
|
+
this.replaceCacheFromSnapshot(body.flags, requestedAt);
|
|
132
|
+
return true;
|
|
133
|
+
} catch (err) {
|
|
134
|
+
console.error("[canarygate] Error fetching flags:", err);
|
|
135
|
+
this.stale = true;
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
applyFlagUpdate(raw) {
|
|
140
|
+
const nextVersion = parseTimestamp(raw.updatedAt);
|
|
141
|
+
const currentVersion = this.cacheVersions.get(raw.key) ?? -1;
|
|
142
|
+
if (nextVersion < currentVersion) return;
|
|
143
|
+
this.cacheVersions.set(raw.key, nextVersion);
|
|
144
|
+
this.cache.set(raw.key, raw);
|
|
145
|
+
}
|
|
146
|
+
applyFlagDeletion(payload) {
|
|
147
|
+
const nextVersion = parseTimestamp(payload.deletedAt);
|
|
148
|
+
const currentVersion = this.cacheVersions.get(payload.key) ?? -1;
|
|
149
|
+
if (nextVersion < currentVersion) return;
|
|
150
|
+
this.cacheVersions.set(payload.key, nextVersion);
|
|
151
|
+
this.cache.delete(payload.key);
|
|
152
|
+
}
|
|
153
|
+
handleStreamMessage(event, data) {
|
|
154
|
+
if (event === "connected" || event === "connection-closing") return;
|
|
155
|
+
if (!data) return;
|
|
156
|
+
try {
|
|
157
|
+
if (event === "flag-deleted") {
|
|
158
|
+
const payload = JSON.parse(data);
|
|
159
|
+
this.applyFlagDeletion(payload);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (event === "flag-updated" || event === "flag-created") {
|
|
163
|
+
this.applyFlagUpdate(JSON.parse(data));
|
|
164
|
+
}
|
|
165
|
+
} catch (err) {
|
|
166
|
+
console.error(`[canarygate] Failed to parse ${event} event:`, err);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
clearHeartbeatTimeout() {
|
|
170
|
+
if (this.heartbeatTimeout) {
|
|
171
|
+
clearTimeout(this.heartbeatTimeout);
|
|
172
|
+
this.heartbeatTimeout = null;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
bumpHeartbeatTimeout(abortController) {
|
|
176
|
+
this.clearHeartbeatTimeout();
|
|
177
|
+
this.heartbeatTimeout = setTimeout(() => {
|
|
178
|
+
if (this.streamAbortController === abortController && !this.destroyed) {
|
|
179
|
+
abortController.abort();
|
|
180
|
+
}
|
|
181
|
+
}, this.heartbeatTimeoutMs);
|
|
182
|
+
}
|
|
183
|
+
scheduleReconnect() {
|
|
184
|
+
if (this.destroyed || this.reconnectTimeout) return;
|
|
185
|
+
const nextDelay = Math.min(
|
|
186
|
+
this.streamRetryDelay * 2 ** this.reconnectAttempts,
|
|
187
|
+
this.maxReconnectDelay
|
|
188
|
+
);
|
|
189
|
+
this.reconnectAttempts += 1;
|
|
190
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
191
|
+
this.reconnectTimeout = null;
|
|
192
|
+
this.connectStream();
|
|
193
|
+
}, nextDelay);
|
|
194
|
+
}
|
|
195
|
+
async consumeStream(abortController) {
|
|
196
|
+
try {
|
|
197
|
+
const headers = { "X-Api-Key": this.apiKey };
|
|
198
|
+
if (this.environment) headers["X-Environment"] = this.environment;
|
|
199
|
+
const response = await fetch(`${this.baseUrl}/sdk/stream`, {
|
|
200
|
+
headers,
|
|
201
|
+
signal: abortController.signal,
|
|
202
|
+
cache: "no-store"
|
|
203
|
+
});
|
|
204
|
+
if (!response.ok) {
|
|
205
|
+
console.error(
|
|
206
|
+
`[canarygate] Failed to connect stream: ${response.status} ${response.statusText}`
|
|
207
|
+
);
|
|
208
|
+
this.stale = true;
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (!response.body) {
|
|
212
|
+
console.error(
|
|
213
|
+
"[canarygate] Stream body is not available in this runtime"
|
|
214
|
+
);
|
|
215
|
+
this.stale = true;
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
this.reconnectAttempts = 0;
|
|
219
|
+
this.bumpHeartbeatTimeout(abortController);
|
|
220
|
+
if (this.stale) {
|
|
221
|
+
await this.fetchFlags();
|
|
222
|
+
}
|
|
223
|
+
const reader = response.body.getReader();
|
|
224
|
+
const decoder = new TextDecoder();
|
|
225
|
+
let buffer = "";
|
|
226
|
+
while (!abortController.signal.aborted) {
|
|
227
|
+
const { done, value } = await reader.read();
|
|
228
|
+
if (done) break;
|
|
229
|
+
this.bumpHeartbeatTimeout(abortController);
|
|
230
|
+
buffer += decoder.decode(value, { stream: true });
|
|
231
|
+
const blocks = buffer.split(/\r?\n\r?\n/);
|
|
232
|
+
buffer = blocks.pop() ?? "";
|
|
233
|
+
for (const block of blocks) {
|
|
234
|
+
const parsedEvent = parseSseEventBlock(block);
|
|
235
|
+
if (!parsedEvent) continue;
|
|
236
|
+
if (parsedEvent.retryMs !== void 0) {
|
|
237
|
+
this.streamRetryDelay = parsedEvent.retryMs;
|
|
238
|
+
}
|
|
239
|
+
this.handleStreamMessage(parsedEvent.event, parsedEvent.data);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
buffer += decoder.decode();
|
|
243
|
+
if (buffer.trim()) {
|
|
244
|
+
const parsedEvent = parseSseEventBlock(buffer);
|
|
245
|
+
if (parsedEvent) {
|
|
246
|
+
if (parsedEvent.retryMs !== void 0) {
|
|
247
|
+
this.streamRetryDelay = parsedEvent.retryMs;
|
|
248
|
+
}
|
|
249
|
+
this.handleStreamMessage(parsedEvent.event, parsedEvent.data);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
} catch (err) {
|
|
253
|
+
if (!isAbortError(err)) {
|
|
254
|
+
console.error("[canarygate] Stream connection failed:", err);
|
|
255
|
+
}
|
|
256
|
+
} finally {
|
|
257
|
+
this.clearHeartbeatTimeout();
|
|
258
|
+
if (this.streamAbortController === abortController) {
|
|
259
|
+
this.streamAbortController = null;
|
|
260
|
+
}
|
|
261
|
+
if (!this.destroyed) {
|
|
262
|
+
this.stale = true;
|
|
263
|
+
this.scheduleReconnect();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
connectStream() {
|
|
268
|
+
if (this.destroyed || this.streamAbortController) return;
|
|
269
|
+
const abortController = new AbortController();
|
|
270
|
+
this.streamAbortController = abortController;
|
|
271
|
+
void this.consumeStream(abortController);
|
|
272
|
+
}
|
|
273
|
+
getFlag(key, context) {
|
|
274
|
+
const raw = this.cache.get(key);
|
|
275
|
+
if (!raw) return void 0;
|
|
276
|
+
const evaluationId = context?.userId || this.anonId;
|
|
277
|
+
if (raw.type === "rollout") {
|
|
278
|
+
const inRollout = raw.enabled && hashString(`${raw.key}:${evaluationId}`) < raw.rolloutPercent;
|
|
279
|
+
return {
|
|
280
|
+
key: raw.key,
|
|
281
|
+
type: "rollout",
|
|
282
|
+
enabled: inRollout,
|
|
283
|
+
percent: raw.rolloutPercent
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
return { key: raw.key, type: "boolean", enabled: raw.enabled };
|
|
287
|
+
}
|
|
288
|
+
getFlags(context) {
|
|
289
|
+
return Array.from(this.cache.keys()).map(
|
|
290
|
+
(key) => this.getFlag(key, context)
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
isStale() {
|
|
294
|
+
return this.stale;
|
|
295
|
+
}
|
|
296
|
+
getLastSyncAt() {
|
|
297
|
+
return this.lastSyncAt;
|
|
298
|
+
}
|
|
299
|
+
disconnect() {
|
|
300
|
+
this.destroyed = true;
|
|
301
|
+
if (this.reconnectTimeout) {
|
|
302
|
+
clearTimeout(this.reconnectTimeout);
|
|
303
|
+
this.reconnectTimeout = null;
|
|
304
|
+
}
|
|
305
|
+
this.clearHeartbeatTimeout();
|
|
306
|
+
this.streamAbortController?.abort();
|
|
307
|
+
this.streamAbortController = null;
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
export {
|
|
312
|
+
CanaryGateBase
|
|
313
|
+
};
|
package/dist/client.d.ts
ADDED