-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
442 lines (384 loc) · 15.6 KB
/
Program.cs
File metadata and controls
442 lines (384 loc) · 15.6 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/**
* C# Flux Starter - Backend Server
*
* A WebSocket proxy server that transparently forwards audio and transcription
* messages between browser clients and Deepgram's Flux API (next-gen streaming
* transcription with turn detection).
*
* Key Features:
* - WebSocket proxy: /api/flux -> wss://api.deepgram.com/v2/listen
* - Bidirectional message forwarding (binary audio + JSON results)
* - JWT session auth with rate limiting (production only)
* - Metadata endpoint: GET /api/metadata
* - CORS enabled for frontend communication
* - Graceful shutdown with connection tracking
*/
using System.Collections.Concurrent;
using System.IdentityModel.Tokens.Jwt;
using System.Net.WebSockets;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;
using Tomlyn;
using Tomlyn.Model;
using HttpResults = Microsoft.AspNetCore.Http.Results;
// ============================================================================
// ENVIRONMENT LOADING
// ============================================================================
DotNetEnv.Env.Load();
// ============================================================================
// CONFIGURATION
// ============================================================================
var port = int.TryParse(Environment.GetEnvironmentVariable("PORT"), out var p) ? p : 8081;
var host = Environment.GetEnvironmentVariable("HOST") ?? "0.0.0.0";
var frontendPort = int.TryParse(Environment.GetEnvironmentVariable("FRONTEND_PORT"), out var fp) ? fp : 8080;
const string DeepgramFluxUrl = "wss://api.deepgram.com/v2/listen";
// ============================================================================
// SESSION AUTH - JWT tokens with rate limiting for production security
// ============================================================================
var sessionSecretEnv = Environment.GetEnvironmentVariable("SESSION_SECRET");
var sessionSecret = sessionSecretEnv ?? Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
var sessionSecretKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(sessionSecret));
const int JwtExpirySeconds = 3600; // 1 hour
string CreateSessionToken()
{
var handler = new JwtSecurityTokenHandler();
var descriptor = new SecurityTokenDescriptor
{
Expires = DateTime.UtcNow.AddSeconds(JwtExpirySeconds),
SigningCredentials = new SigningCredentials(sessionSecretKey, SecurityAlgorithms.HmacSha256Signature),
};
var token = handler.CreateToken(descriptor);
return handler.WriteToken(token);
}
bool ValidateSessionToken(string token)
{
try
{
var handler = new JwtSecurityTokenHandler();
handler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = sessionSecretKey,
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero,
}, out _);
return true;
}
catch
{
return false;
}
}
/// Validates JWT from WebSocket subprotocol: access_token.<jwt>
string? ValidateWsToken(string? protocolHeader)
{
if (string.IsNullOrEmpty(protocolHeader)) return null;
var protocols = protocolHeader.Split(',', StringSplitOptions.TrimEntries);
var tokenProto = protocols.FirstOrDefault(p => p.StartsWith("access_token."));
if (tokenProto == null) return null;
var token = tokenProto["access_token.".Length..];
return ValidateSessionToken(token) ? tokenProto : null;
}
// ============================================================================
// API KEY LOADING
// ============================================================================
static string LoadApiKey()
{
var apiKey = Environment.GetEnvironmentVariable("DEEPGRAM_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.Error.WriteLine("\n❌ ERROR: Deepgram API key not found!\n");
Console.Error.WriteLine("Please set your API key using one of these methods:\n");
Console.Error.WriteLine("1. Create a .env file (recommended):");
Console.Error.WriteLine(" DEEPGRAM_API_KEY=your_api_key_here\n");
Console.Error.WriteLine("2. Environment variable:");
Console.Error.WriteLine(" export DEEPGRAM_API_KEY=your_api_key_here\n");
Console.Error.WriteLine("Get your API key at: https://console.deepgram.com\n");
Environment.Exit(1);
}
return apiKey;
}
var apiKey = LoadApiKey();
// ============================================================================
// SETUP
// ============================================================================
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls($"http://{host}:{port}");
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins(
$"http://localhost:{frontendPort}",
$"http://127.0.0.1:{frontendPort}")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
var app = builder.Build();
app.UseCors();
app.UseWebSockets();
// Track active connections for graceful shutdown
var activeConnections = new ConcurrentDictionary<string, WebSocket>();
// ============================================================================
// SESSION ROUTES - Auth endpoints (unprotected)
// ============================================================================
/// GET /api/session — Issues a JWT for API authentication
app.MapGet("/api/session", () =>
{
var token = CreateSessionToken();
return HttpResults.Json(new Dictionary<string, string> { ["token"] = token });
});
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/// Builds the Deepgram Flux WebSocket URL with query parameters forwarded from the client
static string BuildDeepgramUrl(string? queryString)
{
var uri = new UriBuilder(DeepgramFluxUrl);
var query = System.Web.HttpUtility.ParseQueryString(queryString ?? "");
// Flux uses a hardcoded model and minimal required parameters
var qs = System.Web.HttpUtility.ParseQueryString("");
qs["model"] = "flux-general-en";
qs["encoding"] = query["encoding"] ?? "linear16";
qs["sample_rate"] = query["sample_rate"] ?? "16000";
// Optional flux-specific parameters (only add if provided)
if (!string.IsNullOrEmpty(query["eot_threshold"]))
qs["eot_threshold"] = query["eot_threshold"];
if (!string.IsNullOrEmpty(query["eager_eot_threshold"]))
qs["eager_eot_threshold"] = query["eager_eot_threshold"];
if (!string.IsNullOrEmpty(query["eot_timeout_ms"]))
qs["eot_timeout_ms"] = query["eot_timeout_ms"];
// keyterm is a multi-value parameter
var keyterms = query.GetValues("keyterm");
if (keyterms != null)
{
foreach (var term in keyterms)
qs.Add("keyterm", term);
}
uri.Query = qs.ToString();
return uri.ToString();
}
/// Forwards messages from one WebSocket to another
static async Task ForwardMessages(WebSocket source, WebSocket destination, string direction, CancellationToken ct)
{
var buffer = new byte[8192];
var messageCount = 0;
try
{
while (source.State == WebSocketState.Open && destination.State == WebSocketState.Open)
{
var result = await source.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
if (result.MessageType == WebSocketMessageType.Close)
{
// Propagate close to destination
if (destination.State == WebSocketState.Open)
{
await destination.CloseAsync(
result.CloseStatus ?? WebSocketCloseStatus.NormalClosure,
result.CloseStatusDescription ?? "Connection closed",
ct);
}
break;
}
messageCount++;
var logInterval = direction == "client→deepgram" ? 100 : 10;
var isBinary = result.MessageType == WebSocketMessageType.Binary;
if (messageCount % logInterval == 0 || !isBinary)
{
Console.WriteLine($" {(direction == "client→deepgram" ? "→" : "←")} {direction} #{messageCount} (binary: {isBinary}, size: {result.Count})");
}
if (destination.State == WebSocketState.Open)
{
await destination.SendAsync(
new ArraySegment<byte>(buffer, 0, result.Count),
result.MessageType,
result.EndOfMessage,
ct);
}
}
}
catch (WebSocketException ex)
{
Console.Error.WriteLine($" WebSocket error in {direction}: {ex.Message}");
}
catch (OperationCanceledException)
{
// Shutdown requested
}
}
/// Handles a single WebSocket proxy session between client and Deepgram Flux
async Task HandleFluxStream(WebSocket clientWs, string? queryString, string apiKey, CancellationToken appCt)
{
var connectionId = Guid.NewGuid().ToString("N")[..8];
activeConnections[connectionId] = clientWs;
Console.WriteLine($"[{connectionId}] Client connected to /api/flux");
var deepgramUrl = BuildDeepgramUrl(queryString);
Console.WriteLine($"[{connectionId}] Connecting to Deepgram Flux: {deepgramUrl}");
using var deepgramWs = new ClientWebSocket();
deepgramWs.Options.SetRequestHeader("Authorization", $"Token {apiKey}");
try
{
await deepgramWs.ConnectAsync(new Uri(deepgramUrl), appCt);
Console.WriteLine($"[{connectionId}] ✓ Connected to Deepgram Flux API");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(appCt);
var clientToDeepgram = ForwardMessages(clientWs, deepgramWs, "client→deepgram", cts.Token);
var deepgramToClient = ForwardMessages(deepgramWs, clientWs, "deepgram→client", cts.Token);
// Wait for either direction to complete
await Task.WhenAny(clientToDeepgram, deepgramToClient);
cts.Cancel();
// Allow the other task to finish
try { await Task.WhenAll(clientToDeepgram, deepgramToClient); }
catch (OperationCanceledException) { }
}
catch (WebSocketException ex)
{
Console.Error.WriteLine($"[{connectionId}] Deepgram connection error: {ex.Message}");
if (clientWs.State == WebSocketState.Open)
{
await clientWs.CloseAsync(
WebSocketCloseStatus.InternalServerError,
"Deepgram connection error",
CancellationToken.None);
}
}
catch (OperationCanceledException)
{
// App shutdown
}
finally
{
// Close connections if still open
if (clientWs.State == WebSocketState.Open)
{
try
{
await clientWs.CloseAsync(
WebSocketCloseStatus.NormalClosure,
"Connection ended",
CancellationToken.None);
}
catch { }
}
if (deepgramWs.State == WebSocketState.Open)
{
try
{
await deepgramWs.CloseAsync(
WebSocketCloseStatus.NormalClosure,
"Connection ended",
CancellationToken.None);
}
catch { }
}
activeConnections.TryRemove(connectionId, out _);
Console.WriteLine($"[{connectionId}] Connection closed ({activeConnections.Count} active)");
}
}
// ============================================================================
// WEBSOCKET ENDPOINT
// ============================================================================
app.Use(async (context, next) =>
{
if (context.Request.Path == "/api/flux" && context.WebSockets.IsWebSocketRequest)
{
// Validate JWT from WebSocket subprotocol
var protocolHeader = context.Request.Headers["Sec-WebSocket-Protocol"].FirstOrDefault();
var validProto = ValidateWsToken(protocolHeader);
if (validProto == null)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized");
return;
}
var clientWs = await context.WebSockets.AcceptWebSocketAsync(validProto);
await HandleFluxStream(clientWs, context.Request.QueryString.Value, apiKey, context.RequestAborted);
}
else
{
await next(context);
}
});
// ============================================================================
// API ROUTES
// ============================================================================
// Health check endpoint
app.MapGet("/health", () => HttpResults.Json(new { status = "ok", service = "flux" }));
/// GET /api/metadata
///
/// Returns metadata about this starter application from deepgram.toml
app.MapGet("/api/metadata", () =>
{
try
{
var tomlPath = Path.Combine(Directory.GetCurrentDirectory(), "deepgram.toml");
var tomlContent = File.ReadAllText(tomlPath);
var tomlModel = Toml.ToModel(tomlContent);
if (!tomlModel.ContainsKey("meta") || tomlModel["meta"] is not TomlTable metaTable)
{
return HttpResults.Json(new Dictionary<string, string>
{
["error"] = "INTERNAL_SERVER_ERROR",
["message"] = "Missing [meta] section in deepgram.toml",
}, statusCode: 500);
}
var meta = new Dictionary<string, object?>();
foreach (var kvp in metaTable)
{
meta[kvp.Key] = kvp.Value;
}
return HttpResults.Json(meta);
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error reading metadata: {ex}");
return HttpResults.Json(new Dictionary<string, string>
{
["error"] = "INTERNAL_SERVER_ERROR",
["message"] = "Failed to read metadata from deepgram.toml",
}, statusCode: 500);
}
});
// ============================================================================
// GRACEFUL SHUTDOWN
// ============================================================================
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() =>
{
Console.WriteLine($"\nShutting down... Closing {activeConnections.Count} active connection(s)...");
foreach (var kvp in activeConnections)
{
try
{
if (kvp.Value.State == WebSocketState.Open)
{
kvp.Value.CloseAsync(
WebSocketCloseStatus.EndpointUnavailable,
"Server shutting down",
CancellationToken.None).Wait(TimeSpan.FromSeconds(5));
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error closing connection {kvp.Key}: {ex.Message}");
}
}
Console.WriteLine("All connections closed.");
});
// ============================================================================
// SERVER START
// ============================================================================
Console.WriteLine();
Console.WriteLine(new string('=', 70));
Console.WriteLine($"🚀 Backend API Server running at http://localhost:{port}");
Console.WriteLine($"📡 CORS enabled for http://localhost:{frontendPort}");
Console.WriteLine($"📡 GET /api/session");
Console.WriteLine($"📡 WebSocket endpoint: ws://localhost:{port}/api/flux (auth required)");
Console.WriteLine($"📡 GET /health");
Console.WriteLine($"📡 GET /api/metadata");
Console.WriteLine($"\n💡 Frontend should be running on http://localhost:{frontendPort}");
Console.WriteLine(new string('=', 70));
Console.WriteLine();
app.Run();