Bundle: redb-tsak / src/redb.Tsak.Client (src.redb.Tsak.Client.txt), 5 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak
Index: https://redbase.app/src/dev-2026-12-06/redb-tsak/_index.txt
====
Path: redb-tsak/src/redb.Tsak.Client/ApiException.cs
Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak
Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Client/ApiException.cs
----
using redb.Tsak.Contracts;
namespace redb.Tsak.Client;
///
/// Base exception thrown when the Tsak API returns a non-success status code.
/// Existing catch (ApiException) sites continue to work — typed subclasses below
/// (, , etc.) extend this type
/// for HTTP-status-driven control flow without breaking callers.
///
public class ApiException : Exception
{
/// HTTP status code returned by the API.
public int StatusCode { get; }
/// Parsed error response body, if available.
public ApiErrorResponse? ErrorResponse { get; }
///
/// Initializes a new API exception.
///
/// HTTP status code.
/// Error message.
/// Parsed error response, if available.
public ApiException(int statusCode, string message, ApiErrorResponse? errorResponse = null)
: base(message)
{
StatusCode = statusCode;
ErrorResponse = errorResponse;
}
///
/// Creates a typed subclass matching the HTTP status code.
/// Falls back to the base for status codes without a dedicated type.
///
public static ApiException Create(int statusCode, string message, ApiErrorResponse? errorResponse = null)
=> statusCode switch
{
400 => new BadRequestException(message, errorResponse),
401 => new UnauthorizedException(message, errorResponse),
403 => new ForbiddenException(message, errorResponse),
404 => new NotFoundException(message, errorResponse),
409 => new ConflictException(message, errorResponse),
429 => new ThrottledException(message, errorResponse),
_ => new ApiException(statusCode, message, errorResponse)
};
}
/// HTTP 400 Bad Request — request payload was rejected by the API.
public sealed class BadRequestException : ApiException
{
/// Initializes a new instance.
public BadRequestException(string message, ApiErrorResponse? errorResponse = null)
: base(400, message, errorResponse) { }
}
/// HTTP 401 Unauthorized — credentials missing or invalid.
public sealed class UnauthorizedException : ApiException
{
/// Initializes a new instance.
public UnauthorizedException(string message, ApiErrorResponse? errorResponse = null)
: base(401, message, errorResponse) { }
}
/// HTTP 403 Forbidden — caller authenticated but lacks permission.
public sealed class ForbiddenException : ApiException
{
/// Initializes a new instance.
public ForbiddenException(string message, ApiErrorResponse? errorResponse = null)
: base(403, message, errorResponse) { }
}
/// HTTP 404 Not Found — resource does not exist.
public sealed class NotFoundException : ApiException
{
/// Initializes a new instance.
public NotFoundException(string message, ApiErrorResponse? errorResponse = null)
: base(404, message, errorResponse) { }
}
/// HTTP 409 Conflict — request conflicts with current resource state.
public sealed class ConflictException : ApiException
{
/// Initializes a new instance.
public ConflictException(string message, ApiErrorResponse? errorResponse = null)
: base(409, message, errorResponse) { }
}
/// HTTP 429 Too Many Requests — caller exceeded a rate limit (e.g. AuthThrottle).
public sealed class ThrottledException : ApiException
{
/// Initializes a new instance.
public ThrottledException(string message, ApiErrorResponse? errorResponse = null)
: base(429, message, errorResponse) { }
}
Path: redb-tsak/src/redb.Tsak.Client/ITsakApiClient.cs
Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak
Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Client/ITsakApiClient.cs
----
using redb.Tsak.Contracts;
namespace redb.Tsak.Client;
///
/// Contract for the Tsak runtime REST API client.
/// All methods throw on non-success responses.
///
public interface ITsakApiClient : IDisposable
{
// ── Auth ──────────────────────────────────────────────────────────
/// Create a new API key.
/// Key name.
/// Roles to assign.
/// Optional user ID.
/// Optional expiration timestamp.
/// Cancellation token.
Task CreateApiKeyAsync(string name, string[]? roles = null, string? userId = null, DateTime? expiresAt = null, CancellationToken ct = default);
/// List all API keys.
Task ListApiKeysAsync(CancellationToken ct = default);
/// Revoke an API key by ID.
Task RevokeApiKeyAsync(string id, CancellationToken ct = default);
// ── Cluster ──────────────────────────────────────────────────────
/// Get cluster status.
Task GetClusterStatusAsync(CancellationToken ct = default);
/// List cluster nodes.
Task ListClusterNodesAsync(CancellationToken ct = default);
/// Trigger cluster rebalance.
Task RebalanceClusterAsync(CancellationToken ct = default);
/// Remove a dead/offline cluster node.
Task RemoveClusterNodeAsync(string nodeId, CancellationToken ct = default);
/// Cordon a node (take on no new work; drain to peers) for planned maintenance.
Task CordonNodeAsync(string nodeId, CancellationToken ct = default);
/// Uncordon a node — it starts taking on work again.
Task UncordonNodeAsync(string nodeId, CancellationToken ct = default);
// ── Contexts ─────────────────────────────────────────────────────
/// List all route contexts.
Task ListContextsAsync(CancellationToken ct = default);
/// Get details of a specific context.
Task GetContextAsync(string name, CancellationToken ct = default);
/// Start a context.
Task StartContextAsync(string name, CancellationToken ct = default);
/// Stop a context.
Task StopContextAsync(string name, CancellationToken ct = default);
/// Restart a context.
Task RestartContextAsync(string name, CancellationToken ct = default);
/// Reset persisted route states and restart a context.
Task ResetRouteStatesAsync(string name, CancellationToken ct = default);
/// Remove a context.
Task RemoveContextAsync(string name, CancellationToken ct = default);
// ── Routes ───────────────────────────────────────────────────────
/// List all routes in a context.
Task ListRoutesAsync(string contextName, CancellationToken ct = default);
/// Get detailed info for a specific route.
Task GetRouteAsync(string contextName, string routeId, CancellationToken ct = default);
/// List endpoints for a context.
Task ListEndpointsAsync(string contextName, CancellationToken ct = default);
/// Start a route.
Task StartRouteAsync(string contextName, string routeId, CancellationToken ct = default);
/// Stop a route with optional timeout.
Task StopRouteAsync(string contextName, string routeId, int? timeoutSeconds = null, CancellationToken ct = default);
/// Browse in-flight exchanges for a specific route.
Task GetRouteInflightAsync(string contextName, string routeId, CancellationToken ct = default);
/// Browse all in-flight exchanges across all routes in a context.
Task GetContextInflightAsync(string contextName, CancellationToken ct = default);
// ── Watchdog ─────────────────────────────────────────────────────
/// Get watchdog status and state.
Task GetWatchdogStatusAsync(CancellationToken ct = default);
/// Get active watchdog alerts.
Task GetWatchdogAlertsAsync(CancellationToken ct = default);
/// Enable watchdog monitoring.
Task EnableWatchdogAsync(CancellationToken ct = default);
/// Disable watchdog monitoring.
Task DisableWatchdogAsync(CancellationToken ct = default);
/// Alert-delivery status: whether delivery is active and which channels are enabled.
Task GetAlertStatusAsync(CancellationToken ct = default);
/// Send a synthetic alert through every enabled channel; returns the per-channel outcome.
Task TestAlertAsync(CancellationToken ct = default);
// ── Lifecycle ────────────────────────────────────────────────────
/// Get lifecycle events with optional filters.
Task GetLifecycleEventsAsync(
string? context = null, string? route = null,
string? type = null, DateTime? since = null,
int? limit = null, CancellationToken ct = default);
// ── Metrics & Dashboard ──────────────────────────────────────────
/// Get per-route metrics summary.
Task GetRouteMetricsAsync(string contextName, string routeId, CancellationToken ct = default);
/// Get aggregated dashboard snapshot.
Task GetDashboardAsync(CancellationToken ct = default);
// ── Force-Stop & Diagnostics ─────────────────────────────────────
/// Force-stop a route immediately (no drain).
Task ForceStopRouteAsync(string contextName, string routeId, CancellationToken ct = default);
/// Get full system diagnostic dump.
Task GetDiagnosticDumpAsync(CancellationToken ct = default);
/// Get diagnostic dump for a specific route.
Task GetRouteDiagnosticsAsync(string contextName, string routeId, CancellationToken ct = default);
// ── Logs ─────────────────────────────────────────────────────────
/// Get buffered log entries. Supports incremental fetch via afterId.
Task GetLogsAsync(long? afterId = null, int? limit = null, string? level = null, CancellationToken ct = default);
///
/// Get the buffered log entries older than , newest first: the page before the oldest
/// one shown ("load older"). Empty once the node's buffer holds nothing older.
///
Task GetLogsBeforeAsync(long beforeId, int? limit = null, string? level = null, CancellationToken ct = default);
/// List available log files on the worker node.
Task GetLogFilesAsync(CancellationToken ct = default);
/// Download a log file as ZIP bytes.
Task DownloadLogFileAsync(string filename, CancellationToken ct = default);
// ── Audit ────────────────────────────────────────────────────────
///
/// Query the persistent admin-action audit trail, newest-first. All filters are optional;
/// use / to page (limit is clamped to 1..1000
/// server-side). Returns Available = false when the node runs without a database.
///
Task GetAuditAsync(
string? actor = null,
string? action = null,
string? target = null,
DateTimeOffset? since = null,
DateTimeOffset? until = null,
int? limit = null,
int? offset = null,
CancellationToken ct = default);
// ── Modules ──────────────────────────────────────────────────────
/// List all modules.
Task ListModulesAsync(CancellationToken ct = default);
/// Get details of a specific module.
Task GetModuleAsync(string name, CancellationToken ct = default);
/// Remove a module.
Task RemoveModuleAsync(string name, CancellationToken ct = default);
///
/// Upload a .tpkg package for deployment. is the
/// detached signature (sent as the X-Tsak-Signature header); pass null when unsigned.
/// Requires the node to have upload enabled and the caller to hold the admin role.
///
Task UploadModuleAsync(byte[] packageBytes, string? signatureBase64 = null, CancellationToken ct = default);
/// Dry-run validate a `.tpkg` without installing it.
Task ValidateModuleAsync(byte[] packageBytes, string? signatureBase64 = null, CancellationToken ct = default);
/// Roll a module back to its previous on-disk version.
Task RollbackModuleAsync(string name, CancellationToken ct = default);
// ── Dead-letter queue ────────────────────────────────────────────
/// Query dead-lettered exchanges (failed at a route checkpoint), newest-first, paged.
Task GetFailedExchangesAsync(
string? context = null, string? route = null, string? status = null,
DateTimeOffset? since = null, DateTimeOffset? until = null,
int? limit = null, int? offset = null, CancellationToken ct = default);
/// Replay a dead-lettered exchange: re-run its route tail from the captured snapshot.
Task ReplayExchangeAsync(string entryId, CancellationToken ct = default);
/// Discard a dead-lettered exchange.
Task DiscardExchangeAsync(string entryId, CancellationToken ct = default);
// ── Scheduler ────────────────────────────────────────────────────
/// Get scheduler status.
Task GetSchedulerStatusAsync(CancellationToken ct = default);
/// List scheduled jobs.
Task ListScheduledJobsAsync(CancellationToken ct = default);
/// List currently running jobs.
Task ListRunningJobsAsync(CancellationToken ct = default);
/// Start the scheduler.
Task StartSchedulerAsync(CancellationToken ct = default);
/// Put scheduler in standby mode.
Task StandbySchedulerAsync(CancellationToken ct = default);
/// Pause a specific job.
Task PauseJobAsync(string jobKey, CancellationToken ct = default);
/// Resume a specific job.
Task ResumeJobAsync(string jobKey, CancellationToken ct = default);
/// Fire a scheduled job immediately (out of schedule).
Task FireJobAsync(string jobKey, CancellationToken ct = default);
// Every route context owns its scheduler and a job key is unique within it only. Without a context the key must
// be in exactly one context of the node (otherwise the call fails, naming them); start/standby without a context
// act on every scheduler of the node.
/// Start (or resume from standby) the scheduler of ; all when null.
Task StartSchedulerAsync(string? context, CancellationToken ct = default);
/// Put the scheduler of in standby; all when null.
Task StandbySchedulerAsync(string? context, CancellationToken ct = default);
/// Pause a job of the scheduler of .
Task PauseJobAsync(string jobKey, string? context, CancellationToken ct = default);
/// Resume a job of the scheduler of .
Task ResumeJobAsync(string jobKey, string? context, CancellationToken ct = default);
/// Fire a job of the scheduler of immediately (out of schedule).
Task FireJobAsync(string jobKey, string? context, CancellationToken ct = default);
// ── System ───────────────────────────────────────────────────────
/// Get system health status.
Task GetHealthAsync(CancellationToken ct = default);
/// Get system metrics.
Task GetMetricsAsync(CancellationToken ct = default);
/// Get metrics history over a time window.
Task GetMetricsHistoryAsync(int minutes = 5, CancellationToken ct = default);
/// Get system information.
Task GetInfoAsync(CancellationToken ct = default);
///
/// GET /api/health/deploy: hot swap a new package into this node, or deploy it cold. The 409 of a cold deploy is an
/// answer, not an error: both verdicts come back as the response.
///
Task GetDeployAdviceAsync(CancellationToken ct = default);
/// GET /api/health/deploy/cluster: the same advice for every alive node of the cluster.
Task GetClusterDeployAdviceAsync(CancellationToken ct = default);
/// GET /api/system/assemblies — assemblies actually loaded on the node (Admin only).
Task GetAssembliesAsync(CancellationToken ct = default);
/// Get the effective (merged, redacted) configuration of this node (admin).
Task GetConfigAsync(CancellationToken ct = default);
// ── Users ────────────────────────────────────────────────────────
/// List all users.
Task ListUsersAsync(CancellationToken ct = default);
/// Get user by login.
Task GetUserAsync(string login, CancellationToken ct = default);
/// Create a new user.
Task CreateUserAsync(TsakCreateUserRequest request, CancellationToken ct = default);
/// Update an existing user.
Task UpdateUserAsync(string login, TsakUpdateUserRequest request, CancellationToken ct = default);
/// Delete a user.
Task DeleteUserAsync(string login, CancellationToken ct = default);
// ── Storage ──────────────────────────────────────────────────────
/// Lists the redb instances of this node: the host's own storage and every named one (operator).
Task ListRedbInstancesAsync(CancellationToken ct = default);
///
/// Index and table statistics of one instance plus the window its usage counters cover (operator).
/// Pass no instance for the host's own storage; a named one also needs the context that declares it.
/// This is the call that opens the connection of an instance registered without one.
///
Task GetStorageStatsAsync(string? instance = null, string? context = null, CancellationToken ct = default);
///
/// Refreshes the planner statistics of one table, or of the whole database when no table is named (admin).
/// Runs for minutes on a large database — call it through a control-timeout client.
///
Task AnalyzeStorageAsync(string? instance = null, string? context = null,
string? table = null, string? schema = null, CancellationToken ct = default);
}
Path: redb-tsak/src/redb.Tsak.Client/README.md
Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak
Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Client/README.md
----
# redb.Tsak.Client
> Documentation and articles:
Typed HTTP client for the [redb.Tsak](../../README.md) runtime REST API. Wraps every API endpoint behind a strongly-typed async interface with cancellation support, a configurable timeout, and structured error handling.
## Install
```bash
dotnet add package redb.Tsak.Client
```
The package targets `net10.0` / `net11.0` and has a single dependency: `redb.Tsak.Contracts` (the shared DTO assembly).
4.7 is the last release that targets .NET 8 and .NET 9 (Microsoft's support for both ends on 10 November 2026); from 4.8
the package targets .NET 10 and later.
## Quick start
```csharp
using redb.Tsak.Client;
// Disposable — wrap in using or manage lifetime via DI
using var client = new TsakApiClient(
baseUrl: "http://tsak-host:5100",
apiKey: "sk-your-api-key");
// Get all contexts
var contexts = await client.ListContextsAsync();
foreach (var ctx in contexts)
Console.WriteLine($"{ctx.Name} {ctx.Status} ({ctx.EndpointCount} endpoints)");
```
## Authentication
When the Tsak node has `Tsak:Auth:Enabled = true`, every call (except `/api/system/health`) requires an API key. Pass it to the constructor — the client adds it as the `X-API-Key` header on all requests automatically.
```csharp
var client = new TsakApiClient("http://host:5100", apiKey: "sk-...");
```
If auth is disabled on the node, pass `null` for `apiKey`.
## Timeout
The default timeout is **5 seconds** (`TsakApiClient.DefaultTimeout`). For long-running operations (diagnostics dump, force-stop, module install) override per-client or use a per-call `CancellationToken`:
```csharp
// Longer default for all calls on this client
using var client = new TsakApiClient(baseUrl, apiKey, timeout: TimeSpan.FromSeconds(30));
// Per-call deadline
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60));
var dump = await client.GetDiagnosticDumpAsync(cts.Token);
```
## Interface
`ITsakApiClient` is the full surface. Inject it in your DI container and swap `TsakApiClient` with a test double:
```csharp
services.AddSingleton(_ =>
new TsakApiClient(config["Tsak:Url"], config["Tsak:ApiKey"]));
```
### Auth — API key management
```csharp
// Create a key
var created = await client.CreateApiKeyAsync("ci-bot", roles: ["viewer"]);
Console.WriteLine(created.Key); // Print raw key — not returned again
// List keys
var keys = await client.ListApiKeysAsync();
// Revoke by ID
await client.RevokeApiKeyAsync(keyId);
```
### Contexts
```csharp
var contexts = await client.ListContextsAsync();
var detail = await client.GetContextAsync("orders");
await client.StartContextAsync("orders");
await client.StopContextAsync("orders");
await client.RestartContextAsync("orders");
await client.ResetRouteStatesAsync("orders"); // reset persisted state + restart
await client.RemoveContextAsync("orders");
```
### Routes
```csharp
var routes = await client.ListRoutesAsync("orders");
var route = await client.GetRouteAsync("orders", "in-0");
var endpoints = await client.ListEndpointsAsync("orders");
await client.StartRouteAsync("orders", "in-0");
await client.StopRouteAsync("orders", "in-0", timeoutSeconds: 30);
await client.ForceStopRouteAsync("orders", "in-0"); // no drain
// In-flight exchange inspection
var inflight = await client.GetRouteInflightAsync("orders", "in-0");
var allInflight = await client.GetContextInflightAsync("orders");
```
### Modules
```csharp
var modules = await client.ListModulesAsync();
var mod = await client.GetModuleAsync("Orders");
await client.RemoveModuleAsync("Orders");
```
### Scheduler (Quartz)
```csharp
var status = await client.GetSchedulerStatusAsync();
var jobs = await client.ListScheduledJobsAsync();
var running = await client.ListRunningJobsAsync();
await client.StartSchedulerAsync();
await client.StandbySchedulerAsync();
await client.PauseJobAsync("DEFAULT.my-job");
await client.ResumeJobAsync("DEFAULT.my-job");
```
### Cluster
```csharp
var status = await client.GetClusterStatusAsync();
var nodes = await client.ListClusterNodesAsync();
await client.RebalanceClusterAsync();
await client.RemoveClusterNodeAsync(nodeId);
```
### System health & metrics
```csharp
var health = await client.GetHealthAsync();
var metrics = await client.GetMetricsAsync();
var history = await client.GetMetricsHistoryAsync(minutes: 10);
var info = await client.GetInfoAsync();
```
### Watchdog
```csharp
var state = await client.GetWatchdogStatusAsync();
var alerts = await client.GetWatchdogAlertsAsync();
await client.EnableWatchdogAsync();
await client.DisableWatchdogAsync();
```
### Lifecycle audit log
```csharp
var events = await client.GetLifecycleEventsAsync(
context: "orders",
type: "RouteStarted",
since: DateTime.UtcNow.AddHours(-1),
limit: 50);
```
### Diagnostics
```csharp
var dump = await client.GetDiagnosticDumpAsync();
var routeDump = await client.GetRouteDiagnosticsAsync("orders", "in-0");
var dashboard = await client.GetDashboardAsync();
```
### Logs
```csharp
var logs = await client.GetLogsAsync(limit: 200, level: "Warning");
var logFiles = await client.GetLogFilesAsync();
var zipBytes = await client.DownloadLogFileAsync("tsak-2026-05-07.log");
```
### Users (Pro)
```csharp
var users = await client.ListUsersAsync();
var user = await client.GetUserAsync("alice");
var created = await client.CreateUserAsync(new TsakCreateUserRequest { Login = "bob", ... });
await client.UpdateUserAsync("bob", new TsakUpdateUserRequest { ... });
await client.DeleteUserAsync("bob");
```
## Error handling
All methods throw `ApiException` on non-2xx responses:
```csharp
try
{
await client.StartContextAsync("orders");
}
catch (ApiException ex)
{
Console.Error.WriteLine($"[{ex.StatusCode}] {ex.Message}");
}
```
`ApiException` carries the HTTP status code and server-provided message string.
## API surface summary
| Domain | Methods |
|---|---|
| Auth | `CreateApiKey`, `ListApiKeys`, `RevokeApiKey` |
| Cluster | `GetClusterStatus`, `ListClusterNodes`, `RebalanceCluster`, `RemoveClusterNode` |
| Contexts | `ListContexts`, `GetContext`, `StartContext`, `StopContext`, `RestartContext`, `ResetRouteStates`, `RemoveContext` |
| Routes | `ListRoutes`, `GetRoute`, `ListEndpoints`, `StartRoute`, `StopRoute`, `ForceStopRoute`, `GetRouteInflight`, `GetContextInflight` |
| Modules | `ListModules`, `GetModule`, `RemoveModule` |
| Scheduler | `GetSchedulerStatus`, `ListScheduledJobs`, `ListRunningJobs`, `StartScheduler`, `StandbyScheduler`, `PauseJob`, `ResumeJob` |
| Watchdog | `GetWatchdogStatus`, `GetWatchdogAlerts`, `EnableWatchdog`, `DisableWatchdog` |
| Lifecycle | `GetLifecycleEvents` |
| Metrics | `GetRouteMetrics`, `GetDashboard`, `GetMetrics`, `GetMetricsHistory` |
| Diagnostics | `GetDiagnosticDump`, `GetRouteDiagnostics` |
| Logs | `GetLogs`, `GetLogFiles`, `DownloadLogFile` |
| System | `GetHealth`, `GetInfo` |
| Users | `ListUsers`, `GetUser`, `CreateUser`, `UpdateUser`, `DeleteUser` |
## Related projects
| Project | Role |
|---|---|
| [redb.Tsak.Contracts](../redb.Tsak.Contracts/README.md) | DTO models for all responses |
| [redb.Tsak.CLI](../redb.Tsak.CLI/README.md) | CLI tool built on top of this client |
| [redb.Tsak.Core](../redb.Tsak.Core/README.md) | Server-side implementation of the REST API |
| [redb.Tsak](../../README.md) | Full project overview |
Path: redb-tsak/src/redb.Tsak.Client/TsakApiClient.cs
Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak
Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Client/TsakApiClient.cs
----
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using redb.Tsak.Contracts;
namespace redb.Tsak.Client;
///
/// HTTP implementation of the Tsak runtime API client.
///
public sealed class TsakApiClient : ITsakApiClient
{
/// Default request timeout used when neither the constructor nor a per-call overrides it.
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);
///
/// Default timeout for log-file downloads. The server buffers the whole file into a ZIP before
/// responding, so a large file can take far longer than — a dedicated,
/// longer deadline avoids cutting the download mid-flight (review item 4.9).
///
public static readonly TimeSpan DefaultDownloadTimeout = TimeSpan.FromMinutes(5);
private readonly HttpClient _http;
// Separate client for downloads: the shared 5s HttpClient.Timeout is global and cannot be widened
// per-call, so log-file downloads use their own client with a longer timeout (4.9).
private readonly HttpClient _downloadHttp;
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
};
///
/// Initializes a new Tsak API client.
///
/// Base URL of the Tsak runtime (e.g. http://localhost:5100).
/// Optional API key for authentication.
///
/// Optional default for all requests. Defaults to
/// (5s) — backwards-compatible with the previous behavior. For long-running operations
/// (diagnostics dump, force-stop, module install) pass a larger value here, or supply a
/// per-call with the desired deadline.
///
///
/// Optional timeout for log-file downloads (the dedicated download client). Defaults to
/// (5 min). Independent of so large
/// downloads are not cut by the short default request timeout (review item 4.9).
///
public TsakApiClient(string baseUrl, string? apiKey = null, TimeSpan? timeout = null, TimeSpan? downloadTimeout = null)
{
var baseUri = new Uri(baseUrl.TrimEnd('/') + "/");
_http = new HttpClient { BaseAddress = baseUri, Timeout = timeout ?? DefaultTimeout };
_downloadHttp = new HttpClient { BaseAddress = baseUri, Timeout = downloadTimeout ?? DefaultDownloadTimeout };
if (!string.IsNullOrEmpty(apiKey))
{
_http.DefaultRequestHeaders.Add("X-API-Key", apiKey);
_downloadHttp.DefaultRequestHeaders.Add("X-API-Key", apiKey);
}
}
public void Dispose()
{
_http.Dispose();
_downloadHttp.Dispose();
}
// ── Auth ──────────────────────────────────────────────────────────
///
public async Task CreateApiKeyAsync(
string name, string[]? roles = null, string? userId = null,
DateTime? expiresAt = null, CancellationToken ct = default)
{
var body = new { Name = name, Roles = roles is not null ? string.Join(",", roles) : null, UserId = userId, ExpiresAt = expiresAt };
var response = await _http.PostAsJsonAsync("api/auth/keys", body, ct);
return await ReadAsync(response, ct);
}
///
public async Task ListApiKeysAsync(CancellationToken ct = default)
{
var response = await _http.GetAsync("api/auth/keys", ct);
return await ReadAsync(response, ct);
}
///
public async Task RevokeApiKeyAsync(string id, CancellationToken ct = default)
{
var response = await _http.DeleteAsync($"api/auth/keys/{Uri.EscapeDataString(id)}", ct);
return await ReadAsync(response, ct);
}
// ── Cluster ──────────────────────────────────────────────────────
///
public async Task GetClusterStatusAsync(CancellationToken ct = default)
{
var response = await _http.GetAsync("api/cluster", ct);
return await ReadAsync(response, ct);
}
///
public async Task ListClusterNodesAsync(CancellationToken ct = default)
{
var response = await _http.GetAsync("api/cluster/nodes", ct);
return await ReadAsync(response, ct);
}
///
public async Task RebalanceClusterAsync(CancellationToken ct = default)
{
var response = await _http.PostAsync("api/cluster/rebalance", null, ct);
return await ReadAsync(response, ct);
}
public async Task RemoveClusterNodeAsync(string nodeId, CancellationToken ct = default)
{
var response = await _http.DeleteAsync($"api/cluster/nodes/{Uri.EscapeDataString(nodeId)}", ct);
return await ReadAsync(response, ct);
}
///
public async Task CordonNodeAsync(string nodeId, CancellationToken ct = default)
{
var response = await _http.PostAsync($"api/cluster/nodes/{Uri.EscapeDataString(nodeId)}/cordon", null, ct);
return await ReadAsync(response, ct);
}
///
public async Task UncordonNodeAsync(string nodeId, CancellationToken ct = default)
{
var response = await _http.PostAsync($"api/cluster/nodes/{Uri.EscapeDataString(nodeId)}/uncordon", null, ct);
return await ReadAsync(response, ct);
}
// ── Contexts ─────────────────────────────────────────────────────
///
public async Task ListContextsAsync(CancellationToken ct = default)
{
var response = await _http.GetAsync("api/contexts", ct);
return await ReadAsync(response, ct);
}
///
public async Task GetContextAsync(string name, CancellationToken ct = default)
{
var response = await _http.GetAsync($"api/contexts/{Uri.EscapeDataString(name)}", ct);
return await ReadAsync(response, ct);
}
///
public async Task StartContextAsync(string name, CancellationToken ct = default)
{
var response = await _http.PostAsync($"api/contexts/{Uri.EscapeDataString(name)}/start", null, ct);
return await ReadAsync(response, ct);
}
///
public async Task StopContextAsync(string name, CancellationToken ct = default)
{
var response = await _http.PostAsync($"api/contexts/{Uri.EscapeDataString(name)}/stop", null, ct);
return await ReadAsync(response, ct);
}
///
public async Task RestartContextAsync(string name, CancellationToken ct = default)
{
var response = await _http.PostAsync($"api/contexts/{Uri.EscapeDataString(name)}/restart", null, ct);
return await ReadAsync(response, ct);
}
///
public async Task ResetRouteStatesAsync(string name, CancellationToken ct = default)
{
var response = await _http.PostAsync($"api/contexts/{Uri.EscapeDataString(name)}/reset-route-states", null, ct);
return await ReadAsync(response, ct);
}
///
public async Task RemoveContextAsync(string name, CancellationToken ct = default)
{
var response = await _http.DeleteAsync($"api/contexts/{Uri.EscapeDataString(name)}", ct);
return await ReadAsync(response, ct);
}
// ── Routes ────────────────────────────────────────────────────────
///
public async Task ListRoutesAsync(string contextName, CancellationToken ct = default)
{
var response = await _http.GetAsync($"api/contexts/{Uri.EscapeDataString(contextName)}/routes", ct);
return await ReadAsync(response, ct);
}
///
public async Task GetRouteAsync(string contextName, string routeId, CancellationToken ct = default)
{
var response = await _http.GetAsync($"api/contexts/{Uri.EscapeDataString(contextName)}/routes/{Uri.EscapeDataString(routeId)}", ct);
return await ReadAsync(response, ct);
}
///
public async Task ListEndpointsAsync(string contextName, CancellationToken ct = default)
{
var response = await _http.GetAsync($"api/contexts/{Uri.EscapeDataString(contextName)}/endpoints", ct);
return await ReadAsync(response, ct);
}
///
public async Task StartRouteAsync(string contextName, string routeId, CancellationToken ct = default)
{
var response = await _http.PostAsync($"api/contexts/{Uri.EscapeDataString(contextName)}/routes/{Uri.EscapeDataString(routeId)}/start", null, ct);
return await ReadAsync(response, ct);
}
///
public async Task StopRouteAsync(string contextName, string routeId, int? timeoutSeconds = null, CancellationToken ct = default)
{
var query = timeoutSeconds.HasValue ? $"?timeoutSeconds={timeoutSeconds.Value}" : "";
var response = await _http.PostAsync($"api/contexts/{Uri.EscapeDataString(contextName)}/routes/{Uri.EscapeDataString(routeId)}/stop{query}", null, ct);
return await ReadAsync(response, ct);
}
///
public async Task GetRouteInflightAsync(string contextName, string routeId, CancellationToken ct = default)
{
var response = await _http.GetAsync($"api/contexts/{Uri.EscapeDataString(contextName)}/routes/{Uri.EscapeDataString(routeId)}/inflight", ct);
return await ReadAsync(response, ct);
}
///
public async Task GetContextInflightAsync(string contextName, CancellationToken ct = default)
{
var response = await _http.GetAsync($"api/contexts/{Uri.EscapeDataString(contextName)}/inflight", ct);
return await ReadAsync(response, ct);
}
// ── Watchdog ─────────────────────────────────────────────────────
///
public async Task GetWatchdogStatusAsync(CancellationToken ct = default)
{
var response = await _http.GetAsync("api/watchdog/status", ct);
return await ReadAsync(response, ct);
}
///
public async Task GetWatchdogAlertsAsync(CancellationToken ct = default)
{
var response = await _http.GetAsync("api/watchdog/alerts", ct);
return await ReadAsync(response, ct);
}
///
public async Task EnableWatchdogAsync(CancellationToken ct = default)
{
var response = await _http.PostAsync("api/watchdog/enable", null, ct);
if (!response.IsSuccessStatusCode)
await ReadAsync