-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathofrep-handler.ts
More file actions
287 lines (256 loc) · 8.04 KB
/
ofrep-handler.ts
File metadata and controls
287 lines (256 loc) · 8.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import { ErrorCode, StandardResolutionReasons } from '@openfeature/core';
import type { JsonValue } from '@openfeature/core';
import { FlagStore } from './flag-store';
import {
toEvaluationContext,
type OfrepHandlerOptions,
type OfrepEvaluationRequest,
type OfrepBulkEvaluationRequest,
type OfrepEvaluationSuccess,
type OfrepEvaluationFailure,
type OfrepBulkEvaluationSuccess,
type OfrepReason,
type OfrepErrorCode,
} from './types';
/**
* Map OpenFeature resolution reason to OFREP reason
*/
function toOfrepReason(reason: string | undefined): OfrepReason {
switch (reason) {
case StandardResolutionReasons.STATIC:
return 'STATIC';
case StandardResolutionReasons.TARGETING_MATCH:
return 'TARGETING_MATCH';
case StandardResolutionReasons.SPLIT:
return 'SPLIT';
case StandardResolutionReasons.DISABLED:
return 'DISABLED';
case StandardResolutionReasons.DEFAULT:
return 'DEFAULT';
case StandardResolutionReasons.ERROR:
return 'ERROR';
default:
return 'UNKNOWN';
}
}
/**
* Map OpenFeature error code to OFREP error code
*/
function toOfrepErrorCode(errorCode: string | undefined): OfrepErrorCode {
switch (errorCode) {
case ErrorCode.FLAG_NOT_FOUND:
return 'FLAG_NOT_FOUND';
case ErrorCode.PARSE_ERROR:
return 'PARSE_ERROR';
case ErrorCode.TARGETING_KEY_MISSING:
return 'TARGETING_KEY_MISSING';
case ErrorCode.INVALID_CONTEXT:
return 'INVALID_CONTEXT';
case ErrorCode.TYPE_MISMATCH:
return 'TYPE_MISMATCH';
default:
return 'GENERAL';
}
}
/**
* Create CORS headers for responses
*/
function corsHeaders(origin: string): HeadersInit {
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-API-Key, If-None-Match',
'Access-Control-Expose-Headers': 'ETag',
};
}
/**
* Create a JSON response with optional CORS headers
*/
function jsonResponse(data: unknown, status: number, options: { cors?: boolean; corsOrigin?: string } = {}): Response {
const headers: HeadersInit = {
'Content-Type': 'application/json',
};
if (options.cors !== false) {
Object.assign(headers, corsHeaders(options.corsOrigin || '*'));
}
return new Response(JSON.stringify(data), { status, headers });
}
/**
* OFREP request handler for Cloudflare Workers.
* Handles OFREP API endpoints for flag evaluation.
*/
export class OfrepHandler {
private readonly store: FlagStore;
private readonly basePath: string;
private readonly cors: boolean;
private readonly corsOrigin: string;
constructor(options: OfrepHandlerOptions) {
this.store = new FlagStore(options.staticFlags);
this.basePath = options.basePath || '/ofrep/v1';
this.cors = options.cors !== false;
this.corsOrigin = options.corsOrigin || '*';
}
/**
* Update the flag configuration
*/
setFlags(flags: string | object): void {
this.store.setFlags(flags);
}
/**
* Handle an incoming request
*/
async handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
const path = url.pathname;
// Handle CORS preflight
if (request.method === 'OPTIONS') {
return this.handleOptions();
}
// Route to appropriate handler
const evaluateFlagsPath = `${this.basePath}/evaluate/flags`;
if (path === evaluateFlagsPath && request.method === 'POST') {
return this.handleBulkEvaluation(request);
}
if (path.startsWith(`${evaluateFlagsPath}/`) && request.method === 'POST') {
const flagKey = path.slice(evaluateFlagsPath.length + 1);
if (flagKey) {
return this.handleSingleEvaluation(request, flagKey);
}
}
// Not found
return jsonResponse({ errorDetails: 'Not found' }, 404, { cors: this.cors, corsOrigin: this.corsOrigin });
}
/**
* Handle CORS preflight request
*/
private handleOptions(): Response {
return new Response(null, {
status: 204,
headers: corsHeaders(this.corsOrigin),
});
}
/**
* Handle single flag evaluation: POST /ofrep/v1/evaluate/flags/{key}
*/
private async handleSingleEvaluation(request: Request, flagKey: string): Promise<Response> {
let body: OfrepEvaluationRequest = {};
try {
const text = await request.text();
if (text) {
body = JSON.parse(text);
}
} catch {
return jsonResponse(
{
key: flagKey,
errorCode: 'PARSE_ERROR',
errorDetails: 'Invalid JSON in request body',
},
400,
{ cors: this.cors, corsOrigin: this.corsOrigin },
);
}
const context = toEvaluationContext(body.context);
const result = this.store.resolveValue(flagKey, context);
// Handle flag not found
if (result.errorCode === 'FLAG_NOT_FOUND') {
return jsonResponse(
{
key: flagKey,
errorCode: 'FLAG_NOT_FOUND',
errorDetails: result.errorMessage,
metadata: result.flagMetadata,
},
404,
{ cors: this.cors, corsOrigin: this.corsOrigin },
);
}
// Handle evaluation errors
if (result.reason === 'ERROR' || result.reason === StandardResolutionReasons.ERROR) {
return jsonResponse(
{
key: flagKey,
errorCode: toOfrepErrorCode(result.errorCode),
errorDetails: result.errorMessage,
metadata: result.flagMetadata,
},
400,
{ cors: this.cors, corsOrigin: this.corsOrigin },
);
}
// Success response
const response: OfrepEvaluationSuccess = {
key: flagKey,
value: result.value,
reason: toOfrepReason(result.reason),
variant: result.variant,
metadata: result.flagMetadata as Record<string, JsonValue> | undefined,
};
return jsonResponse(response, 200, { cors: this.cors, corsOrigin: this.corsOrigin });
}
/**
* Handle bulk flag evaluation: POST /ofrep/v1/evaluate/flags
*/
private async handleBulkEvaluation(request: Request): Promise<Response> {
let body: OfrepBulkEvaluationRequest = {};
try {
const text = await request.text();
if (text) {
body = JSON.parse(text);
}
} catch {
return jsonResponse(
{
errorCode: 'PARSE_ERROR',
errorDetails: 'Invalid JSON in request body',
},
400,
{ cors: this.cors, corsOrigin: this.corsOrigin },
);
}
const context = toEvaluationContext(body.context);
const evaluations = this.store.resolveAll(context);
const flags: Array<OfrepEvaluationSuccess | OfrepEvaluationFailure> = evaluations.map((evaluation) => {
if (evaluation.errorCode) {
return {
key: evaluation.flagKey,
errorCode: toOfrepErrorCode(evaluation.errorCode),
errorDetails: evaluation.errorMessage,
metadata: evaluation.flagMetadata as Record<string, JsonValue> | undefined,
} as OfrepEvaluationFailure;
}
return {
key: evaluation.flagKey,
value: evaluation.value,
reason: toOfrepReason(evaluation.reason),
variant: evaluation.variant,
metadata: evaluation.flagMetadata as Record<string, JsonValue> | undefined,
} as OfrepEvaluationSuccess;
});
const response: OfrepBulkEvaluationSuccess = {
flags,
metadata: this.store.getMetadata() as Record<string, JsonValue>,
};
// TODO: Implement ETag for caching
return jsonResponse(response, 200, { cors: this.cors, corsOrigin: this.corsOrigin });
}
}
/**
* Create an OFREP fetch handler for Cloudflare Workers.
*
* @example
* ```typescript
* import { createOfrepHandler } from '@openfeature/flagd-ofrep-cf-worker';
* import flags from './flags.json';
*
* const handler = createOfrepHandler({ staticFlags: flags });
*
* export default {
* fetch: handler,
* };
* ```
*/
export function createOfrepHandler(options: OfrepHandlerOptions): (request: Request) => Promise<Response> {
const handler = new OfrepHandler(options);
return (request: Request) => handler.handleRequest(request);
}