using System.Text.Json.Nodes;
using System.Text.Json;
using System.Security.Cryptography;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Space.Contracts;
namespace XFEWorkflow.Space.Server;
public sealed partial class SpaceStore
{
private async Task<JsonNode> WorkflowPreviewAsync(JsonObject input, SpaceUser? user = null)
{
var publication = Profile.Read(p => WorkflowJson.Clone(p.InstanceWorkflowPublications.SingleOrDefault(x => x.Id == input.String("id"))));
if (publication is null) throw new FileNotFoundException("工作流版本不存在");
if (user is null && publication.Status != PublicationStatus.Published) throw new FileNotFoundException("已上架工作流版本不存在");
if (user is not null && user.Role != SpaceRole.Administrator && user.Id != publication.AuthorId) throw new UnauthorizedAccessException("不能预览其他作者的未公开工作流");
var path = WorkflowPackagePath(publication.Id);
await using (var stream = File.OpenRead(path))
if (stream.Length != publication.PackageBytes || !Convert.ToHexString(await SHA256.HashDataAsync(stream)).Equals(publication.Sha256, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("工作流包校验失败");
var definition = WorkflowPackage.Inspect(path);
if (!JsonNode.DeepEquals(JsonSerializer.SerializeToNode(WorkflowSummary.From(definition, publication.Workflow.Version), WorkflowJson.Options), JsonSerializer.SerializeToNode(publication.Workflow, WorkflowJson.Options))) throw new InvalidDataException("工作流内容与目录不一致");
var plugins = Profile.Read(p => WorkflowJson.Clone(p.InstancePublications.Where(x => x.Status == PublicationStatus.Published && definition.PluginVersions.GetValueOrDefault(x.Manifest.Id) == x.Manifest.Version).Select(x => x.Manifest).ToList()));
return Node(new WorkflowPreview { PublicationId = publication.Id, Sha256 = publication.Sha256, Definition = definition, Plugins = plugins });
}
private static SpaceResourceKind ResourceKind(JsonObject input) => input.String("kind", "plugin") switch
{ "plugin" => SpaceResourceKind.Plugin, "workflow" => SpaceResourceKind.Workflow, _ => throw new InvalidDataException("未知资源类型") };
private string WorkflowPackagePath(string id) { RequireId(id); return Path.Combine(Root, "packages", id + ".xfeworkflow"); }
private JsonNode WorkflowCatalog(string route, JsonObject input)
{
var all = Profile.Read(p => WorkflowJson.Clone(p.InstanceWorkflowPublications)).Where(x => x.Status == PublicationStatus.Published);
if (route == "workflows/detail") return Node(all.Where(x => x.Workflow.Id.Equals(input.String("workflowId"), StringComparison.OrdinalIgnoreCase))
.OrderByDescending(x => SemanticVersion.Parse(x.Workflow.Version)).ToList());
var terms = input.String("query").Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var matches = all.Where(x => terms.All(t => $"{x.Workflow.Name} {x.Workflow.Description} {x.Workflow.Id} {x.AuthorName} {string.Join(" ", x.Workflow.PluginVersions.Keys)}".Contains(t, StringComparison.OrdinalIgnoreCase)))
.GroupBy(x => x.Workflow.Id, StringComparer.OrdinalIgnoreCase).Select(x => x.MaxBy(p => SemanticVersion.Parse(p.Workflow.Version))!)
.OrderByDescending(x => x.SubmittedAt).ToList();
return Node(new WorkflowCatalogPage { Total = matches.Count, Items = matches.Skip(Math.Max(0, input.Integer("offset"))).Take(Math.Clamp(input.Integer("limit", 50), 1, 100)).ToList() });
}
private async Task<JsonNode> WorkflowChunkAsync(JsonObject input)
{
var publication = Profile.Read(p => p.InstanceWorkflowPublications.SingleOrDefault(x => x.Id == input.String("id") && x.Status == PublicationStatus.Published)) ?? throw new FileNotFoundException("已上架工作流版本不存在");
var index = input.Integer("index", -1);
if (index < 0 || (long)index * PluginPackage.ChunkBytes >= publication.PackageBytes) throw new InvalidDataException("分片索引越界");
await using var file = File.OpenRead(WorkflowPackagePath(publication.Id)); file.Position = (long)index * PluginPackage.ChunkBytes;
var buffer = new byte[(int)Math.Min(PluginPackage.ChunkBytes, file.Length - file.Position)]; await file.ReadExactlyAsync(buffer);
return Node(new { data = Convert.ToBase64String(buffer), index });
}
// AuthorAsync already holds the serial metadata writer lock for these methods.
private async Task<JsonNode> CompleteWorkflowAsync(UploadSession upload, string staging, SpaceUser user)
{
var workflow = WorkflowPackage.Inspect(staging);
var versions = Profile.Read(p => p.InstanceWorkflowPublications.Where(x => x.Workflow.Id.Equals(workflow.Id, StringComparison.OrdinalIgnoreCase)).ToList());
if (versions.Any(x => x.AuthorId != user.Id)) throw new UnauthorizedAccessException("工作流 ID 已属于其他作者");
if (versions.Any(x => x.Workflow.Version == upload.Version)) throw new InvalidOperationException("工作流版本已经提交,内容不可覆盖");
var publication = new WorkflowPublication { Workflow = WorkflowSummary.From(workflow, upload.Version), AuthorId = user.Id, AuthorName = user.NickName, Sha256 = upload.Sha256, PackageBytes = upload.Length };
File.Move(staging, WorkflowPackagePath(publication.Id), false);
Profile.Update(p => { p.InstanceWorkflowPublications.Add(publication); p.InstanceUploads.RemoveAll(x => x.Id == upload.Id); }); await Profile.SaveAsync();
for (var i = 0; i < upload.ChunkCount; i++) File.Delete(UploadPath(upload.Id, "." + i));
return Node(publication);
}
private async Task<JsonNode> WorkflowReviewAsync(JsonObject input, SpaceUser user, bool authorWithdraw)
{
var review = Profile.Read(p => p.InstanceWorkflowPublications.SingleOrDefault(x => x.Id == input.String("id"))) ?? throw new FileNotFoundException("工作流版本不存在");
if (authorWithdraw) { if (review.AuthorId != user.Id && user.Role != SpaceRole.Administrator) throw new UnauthorizedAccessException("不能下架其他作者的工作流"); }
else Admin(user);
var decision = authorWithdraw ? "withdraw" : input.String("decision");
if (decision is not ("publish" or "reject" or "withdraw")) throw new InvalidDataException("未知审核决定");
if (decision is "publish" or "reject" && review.Status != PublicationStatus.Pending || decision == "withdraw" && review.Status != PublicationStatus.Published)
throw new InvalidOperationException("当前发布状态不允许此操作");
Profile.Update(_ => { review.Status = decision == "publish" ? PublicationStatus.Published : decision == "reject" ? PublicationStatus.Rejected : PublicationStatus.Withdrawn; review.ReviewedAt = DateTimeOffset.UtcNow; review.ReviewReason = input.String("reason"); });
await Profile.SaveAsync(); return Node(review);
}
}
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Security.Cryptography;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Space.Contracts;
namespace XFEWorkflow.Space.Server;
public sealed partial class SpaceStore
{
private async Task<JsonNode> WorkflowPreviewAsync(JsonObject input, SpaceUser? user = null)
{
var publication = Profile.Read(p => WorkflowJson.Clone(p.InstanceWorkflowPublications.SingleOrDefault(x => x.Id == input.String("id"))));
if (publication is null) throw new FileNotFoundException("工作流版本不存在");
if (user is null && publication.Status != PublicationStatus.Published) throw new FileNotFoundException("已上架工作流版本不存在");
if (user is not null && user.Role != SpaceRole.Administrator && user.Id != publication.AuthorId) throw new UnauthorizedAccessException("不能预览其他作者的未公开工作流");
var path = WorkflowPackagePath(publication.Id);
await using (var stream = File.OpenRead(path))
if (stream.Length != publication.PackageBytes || !Convert.ToHexString(await SHA256.HashDataAsync(stream)).Equals(publication.Sha256, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("工作流包校验失败");
var definition = WorkflowPackage.Inspect(path);
if (!JsonNode.DeepEquals(JsonSerializer.SerializeToNode(WorkflowSummary.From(definition, publication.Workflow.Version), WorkflowJson.Options), JsonSerializer.SerializeToNode(publication.Workflow, WorkflowJson.Options))) throw new InvalidDataException("工作流内容与目录不一致");
var plugins = Profile.Read(p => WorkflowJson.Clone(p.InstancePublications.Where(x => x.Status == PublicationStatus.Published && definition.PluginVersions.GetValueOrDefault(x.Manifest.Id) == x.Manifest.Version).Select(x => x.Manifest).ToList()));
return Node(new WorkflowPreview { PublicationId = publication.Id, Sha256 = publication.Sha256, Definition = definition, Plugins = plugins });
}
private static SpaceResourceKind ResourceKind(JsonObject input) => input.String("kind", "plugin") switch
{ "plugin" => SpaceResourceKind.Plugin, "workflow" => SpaceResourceKind.Workflow, _ => throw new InvalidDataException("未知资源类型") };
private string WorkflowPackagePath(string id) { RequireId(id); return Path.Combine(Root, "packages", id + ".xfeworkflow"); }
private JsonNode WorkflowCatalog(string route, JsonObject input)
{
var all = Profile.Read(p => WorkflowJson.Clone(p.InstanceWorkflowPublications)).Where(x => x.Status == PublicationStatus.Published);
if (route == "workflows/detail") return Node(all.Where(x => x.Workflow.Id.Equals(input.String("workflowId"), StringComparison.OrdinalIgnoreCase))
.OrderByDescending(x => SemanticVersion.Parse(x.Workflow.Version)).ToList());
var terms = input.String("query").Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var matches = all.Where(x => terms.All(t => $"{x.Workflow.Name} {x.Workflow.Description} {x.Workflow.Id} {x.AuthorName} {string.Join(" ", x.Workflow.PluginVersions.Keys)}".Contains(t, StringComparison.OrdinalIgnoreCase)))
.GroupBy(x => x.Workflow.Id, StringComparer.OrdinalIgnoreCase).Select(x => x.MaxBy(p => SemanticVersion.Parse(p.Workflow.Version))!)
.OrderByDescending(x => x.SubmittedAt).ToList();
return Node(new WorkflowCatalogPage { Total = matches.Count, Items = matches.Skip(Math.Max(0, input.Integer("offset"))).Take(Math.Clamp(input.Integer("limit", 50), 1, 100)).ToList() });
}
private async Task<JsonNode> WorkflowChunkAsync(JsonObject input)
{
var publication = Profile.Read(p => p.InstanceWorkflowPublications.SingleOrDefault(x => x.Id == input.String("id") && x.Status == PublicationStatus.Published)) ?? throw new FileNotFoundException("已上架工作流版本不存在");
var index = input.Integer("index", -1);
if (index < 0 || (long)index * PluginPackage.ChunkBytes >= publication.PackageBytes) throw new InvalidDataException("分片索引越界");
await using var file = File.OpenRead(WorkflowPackagePath(publication.Id)); file.Position = (long)index * PluginPackage.ChunkBytes;
var buffer = new byte[(int)Math.Min(PluginPackage.ChunkBytes, file.Length - file.Position)]; await file.ReadExactlyAsync(buffer);
return Node(new { data = Convert.ToBase64String(buffer), index });
}
// AuthorAsync already holds the serial metadata writer lock for these methods.
private async Task<JsonNode> CompleteWorkflowAsync(UploadSession upload, string staging, SpaceUser user)
{
var workflow = WorkflowPackage.Inspect(staging);
var versions = Profile.Read(p => p.InstanceWorkflowPublications.Where(x => x.Workflow.Id.Equals(workflow.Id, StringComparison.OrdinalIgnoreCase)).ToList());
if (versions.Any(x => x.AuthorId != user.Id)) throw new UnauthorizedAccessException("工作流 ID 已属于其他作者");
if (versions.Any(x => x.Workflow.Version == upload.Version)) throw new InvalidOperationException("工作流版本已经提交,内容不可覆盖");
var publication = new WorkflowPublication { Workflow = WorkflowSummary.From(workflow, upload.Version), AuthorId = user.Id, AuthorName = user.NickName, Sha256 = upload.Sha256, PackageBytes = upload.Length };
File.Move(staging, WorkflowPackagePath(publication.Id), false);
Profile.Update(p => { p.InstanceWorkflowPublications.Add(publication); p.InstanceUploads.RemoveAll(x => x.Id == upload.Id); }); await Profile.SaveAsync();
for (var i = 0; i < upload.ChunkCount; i++) File.Delete(UploadPath(upload.Id, "." + i));
return Node(publication);
}
private async Task<JsonNode> WorkflowReviewAsync(JsonObject input, SpaceUser user, bool authorWithdraw)
{
var review = Profile.Read(p => p.InstanceWorkflowPublications.SingleOrDefault(x => x.Id == input.String("id"))) ?? throw new FileNotFoundException("工作流版本不存在");
if (authorWithdraw) { if (review.AuthorId != user.Id && user.Role != SpaceRole.Administrator) throw new UnauthorizedAccessException("不能下架其他作者的工作流"); }
else Admin(user);
var decision = authorWithdraw ? "withdraw" : input.String("decision");
if (decision is not ("publish" or "reject" or "withdraw")) throw new InvalidDataException("未知审核决定");
if (decision is "publish" or "reject" && review.Status != PublicationStatus.Pending || decision == "withdraw" && review.Status != PublicationStatus.Published)
throw new InvalidOperationException("当前发布状态不允许此操作");
Profile.Update(_ => { review.Status = decision == "publish" ? PublicationStatus.Published : decision == "reject" ? PublicationStatus.Rejected : PublicationStatus.Withdrawn; review.ReviewedAt = DateTimeOffset.UtcNow; review.ReviewReason = input.String("reason"); });
await Profile.SaveAsync(); return Node(review);
}
}