using System.Net;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.Data.Projects;
///
/// A sequence of a Chronos Server as its projects' home (owner review 2, R8, phase 5b): the server's
/// /api/v1/sequences/{sid}/projects through , read into the model a workspace works with
/// (), so a workspace pushes to and pulls from a server as it does with this PC's archive. A
/// server out of reach (no answer, a timeout, a certificate it no longer presents, an answer that is not the API's), a
/// sign-in that expired, a sequence the server holds busy or an archive offline there (503), a project file it cannot write
/// for now and a server that keeps no projects are s: the workspace shows Offline and
/// its work waits. A sequence, project or version the server does not have, and a name it refuses, are
/// s as on this PC's archive; anything else (an account without the right, a request the
/// server takes for wrong) keeps its . A push answers its outcome without throwing (a
/// divergence carries the head). The client is the caller's: the home never disposes it, and a client disposed meanwhile
/// (the session ended) is a home out of reach.
///
public sealed class ServerProjectHome : IProjectHome
{
/// The largest page of versions the server answers.
private const int MaxPage = 200;
/// The server's name as its server/info gives it, for the project file; the address's host when null.
public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null)
{
ArgumentNullException.ThrowIfNull(client);
Client = client;
SequenceId = sequenceId;
Server = SyncService.ServerKey(client.BaseAddress);
ServerName = string.IsNullOrWhiteSpace(serverName) ? client.BaseAddress.Host : serverName.Trim();
}
public ChronosClient Client { get; }
/// The server's sequence.
public Guid SequenceId { get; }
/// The server as workspace projects and sync links name it ().
public string Server { get; }
public string ServerName { get; }
/// The home of a workspace project of this server's sequence.
public BundleHome Home => new(BundleHome.ServerKind, SequenceId, null, Server);
///
/// A project file names an archive by id: a server's sequences carry one made from the server's key
/// (), with the server's name and no path.
///
public Task SequenceAsync(CancellationToken cancellationToken) =>
Reach(async () =>
{
var sequence = await Client.GetSequenceAsync(SequenceId, cancellationToken).ConfigureAwait(false);
return new HomeSequence(new BundleArchive(ArchiveIdOf(Server), ServerName, null), new BundleSequence(sequence.Id, sequence.Folder, sequence.DisplayTitle,
sequence.FrameCount), Home);
}, cancellationToken);
///
/// The archive id a server's sequences carry in a workspace's project file, which names one: the same for every
/// sequence of (), made from its key (a version 8 UUID),
/// never one of this PC's archives.
///
public static Guid ArchiveIdOf(string server)
{
ArgumentNullException.ThrowIfNull(server);
var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes("chronos-server-archive:" + server));
hash[6] = (byte)((hash[6] & 0x0F) | 0x80);
hash[8] = (byte)((hash[8] & 0x3F) | 0x80);
return new Guid(hash.AsSpan(0, 16), bigEndian: true);
}
public Task> ListAsync(CancellationToken cancellationToken) =>
Reach>(async () =>
[.. (await Client.ListProjectsAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Select(ProjectWire.ToProject)], cancellationToken);
/// The server records the account that makes the project as its maker, whatever says.
public Task CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToProject(await Client.CreateProjectAsync(SequenceId, new CreateProjectRequest(name, fromVersionId), cancellationToken)
.ConfigureAwait(false)), cancellationToken);
public Task HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToVersion(await Client.GetProjectHeadAsync(SequenceId, projectId, cancellationToken).ConfigureAwait(false)), cancellationToken);
public Task GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(async () => await Client.GetProjectVersionAsync(SequenceId, projectId, versionId, cancellationToken).ConfigureAwait(false) is { } version
? ProjectWire.ToVersion(version)
: null, cancellationToken);
public Task> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach>(async () =>
[
.. (await Client.ListProjectVersionsAsync(SequenceId, projectId, after: Math.Max(0, afterNumber), limit: Page(limit), ct: cancellationToken)
.ConfigureAwait(false)).Items.Select(ProjectWire.ToVersion),
], cancellationToken);
public Task> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach>(async () =>
[
.. (await Client.ListProjectVersionsAsync(SequenceId, projectId, before: beforeNumber is { } before ? Math.Max(0, before) : null, limit: Page(limit),
ct: cancellationToken).ConfigureAwait(false)).Items.Select(ProjectWire.ToVersion),
], cancellationToken);
/// The server numbers the version (head + 1) and records the account that pushed it as its author.
public Task PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(version);
return Reach(async () => ProjectWire.ToResult(await Client.PushProjectVersionAsync(SequenceId, projectId, ProjectWire.ToDto(version), cancellationToken)
.ConfigureAwait(false)), cancellationToken);
}
public Task FramesAsync(CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToHomeFrames(await Client.GetProjectFramesAsync(SequenceId, cancellationToken).ConfigureAwait(false)), cancellationToken);
public Task RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToProject(await Client.RenameProjectAsync(SequenceId, projectId, name, cancellationToken).ConfigureAwait(false)),
cancellationToken);
public Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Client.DeleteProjectAsync(SequenceId, projectId, cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
///
/// Whether says a server is out of reach for now (see the class remarks), not that it
/// refused: what a workspace waits out.
///
public static bool IsUnavailable(Exception exception, CancellationToken cancellationToken = default) => exception switch
{
HomeUnavailableException => true,
// A refusal for good, which is an IOException too.
Workspaces.WorkspaceSyncException => false,
ChronosApiException api => Unavailable(api),
UntrustedCertificateException or HttpRequestException or JsonException or ObjectDisposedException => true,
// A timeout of the client's (not the caller's cancellation).
OperationCanceledException => !cancellationToken.IsCancellationRequested,
IOException => true,
_ => false,
};
private static int Page(int limit) => Math.Clamp(limit, 1, MaxPage);
/// A refusal of the server as this PC's archive gives it, or a server out of reach.
private static async Task Reach(Func> call, CancellationToken cancellationToken)
{
try
{
return await call().ConfigureAwait(false);
}
catch (ChronosApiException ex) when (Refusal(ex) is { } refusal)
{
throw refusal;
}
catch (Exception ex) when (ex is not ProjectException && IsUnavailable(ex, cancellationToken))
{
throw new HomeUnavailableException(ex is ChronosApiException { Status: HttpStatusCode.Unauthorized }
? $"The sign-in on the server expired: {ex.Message}"
: $"The server cannot be reached: {ex.Message}", ex);
}
}
/// The project error a refusal stands for (a sequence, project or version the server does not have, a name it refuses); null for any other.
private static ProjectException? Refusal(ChronosApiException ex) => (ex.Status, ex.Error.Code, ex.Error.Details) switch
{
(HttpStatusCode.NotFound, _, "sequence") => new ProjectException(ProjectError.SequenceNotFound, ex.Message),
(HttpStatusCode.NotFound, _, "project" or "version") => new ProjectException(ProjectError.NotFound, ex.Message),
(HttpStatusCode.BadRequest, ProjectErrors.InvalidName, _) => new ProjectException(ProjectError.InvalidName, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.NameTaken, _) => new ProjectException(ProjectError.NameTaken, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.MainCannotBeDeleted, _) => new ProjectException(ProjectError.MainCannotBeDeleted, ex.Message),
_ => null,
};
///
/// An answer that says the server cannot serve the call for now: busy, its archive offline or its sequence's folder
/// moved (503), a gateway or a timeout, the sign-in expired (401), a project file it cannot write now (409
/// folder_in_use), a server without the projects (404 with nothing named: the API's fallback), or a success
/// that is no answer of the API (a portal's or a proxy's page).
///
private static bool Unavailable(ChronosApiException ex) =>
ex.IsTransient
|| ex.Status == HttpStatusCode.Unauthorized
|| (int)ex.Status is >= 200 and < 300
|| ex is { Status: HttpStatusCode.Conflict, Error.Code: "folder_in_use" }
|| ex is { Status: HttpStatusCode.NotFound, Error.Details: null or "" };
}