分布式部署

从多个节点提供单个文档

当多个节点提供相同的文档时,渲染文档的节点不一定是响应浏览器页面请求的节点。Doconut 将此工作拆分为两个明确的部分——写入端,将文档的制品发布到共享存储;以及读取端,从任意节点提供这些制品。

单个节点不需要这些:常规的 OpenDocumentAsync 路径会将文档保存在该节点的内存中并绑定到浏览器会话(参见会话与安全)。当页面请求可能落在从未打开过文档的节点时,请使用此页面。

两个部分如何配合

text
node A            open request
                      -> PublishAsync(...)   writes pages, document info,
                                             search index and metadata
                                             into  RootPath/{token}/
                      -> returns the token

node B            ?token=...&page=7
                      -> UseDoconutCloud<FileShareCloudHandler>
                      -> reads RootPath/{token}/ and serves the page

两个部分都需要的共享配置

发布者使用 FileShareConfig 进行写入,读取处理程序使用相同的对象进行提供。**如果 RootPath 或 UsePerTokenSubfolders 在两者之间不一致,另一节点将返回 404。**请在唯一位置构建配置并只注册一次,以便两个部分读取相同的对象:

csharp
var rootPath = builder.Configuration["Doconut:SharedRoot"]!;   // 例如 \\fileserver\doconut
builder.Services.AddSingleton(SharedStore.Config(rootPath, asyncPublish: false));

internal static class SharedStore
{
    public static FileShareConfig Config(string rootPath, bool asyncPublish) => new()
    {
        Location              = CloudLocation.FileShare,
        RootPath              = rootPath,
        UsePerTokenSubfolders = true,
        ReadReadyPollMs       = asyncPublish ? 250 : 0,
    };
}

在启用后台发布时传入 asyncPublish: true。

FileShareConfig 位于 Doconut.Clouds,与 AzureConfig、AmazonConfig、GoogleCloudConfig、DropBoxConfig、RedisConfig、CDNConfig 和 FTPConfig 一起。

属性用途
Location用于 UNC/本地共享的 CloudLocation.FileShare
RootPath每个节点都能访问的共享文件夹
UsePerTokenSubfolders将每个文档的制品保存在其各自的 {token} 文件夹中(默认 true)
ReadReadyPollMs读取端等待后台发布仍在写入的页面的时长;0(默认)检查一次。对同步发布的文档没有影响

写入端 — 发布文档

注入 DistributedDocumentPublisher 并进行发布,而不是打开本地会话。一次调用即可渲染并写入完整的制品集——页面、文档信息、搜索索引和元数据——并在完成后返回:

csharp
app.MapPost("/api/open", async (string fileName, FileShareConfig shareConfig,
    DistributedDocumentPublisher publisher, CancellationToken ct) =>
{
    var path            = Path.Combine("files", Path.GetFileName(fileName));
    var config          = new PdfConfig { AllowSearch = true };
    var documentOptions = new DocOptions { TimeOut = 60 };
    var publishOptions  = new DistributedDocumentPublishOptions { CleanUpStagingDirectory = true };

    DistributedDocumentPublishResult result = await publisher.PublishAsync(
        path, shareConfig, config, documentOptions, publishOptions, ct);

    return Results.Text(result.Token);
});

DistributedDocumentPublishResult 包含 Token、ArtifactPath、TotalPages 和 Format。该令牌会像普通查看器令牌一样发送到浏览器。在集群中,端点还会返回签名访问票——参见跨节点安全。

读取端 — 从共享提供服务

在客户端调用的分支上挂载 FileShare 处理程序 — /doconut,匹配 BasePath: 'doconut' — 位于票据检查之后:

csharp
var app = builder.Build();

app.UseDoconutResources();
app.Map("/doconut", branch =>
{
    branch.UseDoconutDistributedDocumentSecurity();   // 已签名的票据 — 请参见下文
    branch.UseDoconutCloud<FileShareCloudHandler>(options =>
    {
        options.Location          = CloudLocation.FileShare;
        options.CloudUploadConfig = app.Services.GetRequiredService<FileShareConfig>();
    }, "/");
});

UseDoconutCloud 将提供者作为其类型参数。处理程序命名为 <Provider>CloudHandler — FileShareCloudHandler、AzureCloudHandler、AmazonS3CloudHandler、GoogleCloudHandler、DropBoxCloudHandler、RedisCloudHandler、FTPCloudHandler 和 CDNCloudHandler。使用路径前缀 "/",该处理程序会响应到达其分支的所有请求。

CDN 处理程序是 只读 — 它提供已经在 CDN 上的内容;不会上传。

可选:在后台发布

默认情况下,PublishAsync 在返回之前渲染完整文档。要在令牌生成后立即返回,并让托管的工作者渲染到同一文件夹,注册可选队列,并使用 asyncPublish: true 构建共享配置:

csharp
builder.Services.AddDoconut(options => { /* … */ });
builder.Services.AddDoconutDistributedAsyncPublish();

如果未进行此注册,则不会有任何注册,发布保持同步,完全如之前一样。

然后调用 EnqueueAsync 而不是 PublishAsync。(DistributedDocumentPublishOptions.Async 只是一个标志,供您自己的代码读取以在两条路径之间选择;发布者会忽略它。)队列是有界的:当它饱和时,EnqueueAsync 抛出 DistributedPublishQueueFullException。使用 503 和 Retry-After 头部来响应,以便客户端退避而不是卡住:

csharp
app.MapPost("/api/open", async (string fileName, FileShareConfig shareConfig,
    IDistributedPublishQueue publishQueue, HttpResponse response, CancellationToken ct) =>
{
    var path            = Path.Combine("files", Path.GetFileName(fileName));
    var config          = new PdfConfig { AllowSearch = true };
    var documentOptions = new DocOptions { TimeOut = 60 };
    var publishOptions  = new DistributedDocumentPublishOptions { FirstPagePriority = true };

    try
    {
        var token = await publishQueue.EnqueueAsync(
            path, shareConfig, config, documentOptions, publishOptions, ct);
        return Results.Text(token);
    }
    catch (DistributedPublishQueueFullException)
    {
        response.Headers["Retry-After"] = "5";
        return Results.StatusCode(503);
    }
});

尚未写入的页面:HTTP 202

使用后台发布时,页面请求可能在工作者写入该页面之前到达。读取端会等待最多 ReadReadyPollMs,随后返回 HTTP 202 Accepted 而不是阻塞请求。

FirstPagePriority = true 缩短了首次查看的等待时间:页面 1 首先写入文档的文件夹,因此文档在后续页面仍在渲染时即可打开。它仅适用于写入每个令牌文件夹的后台发布(UsePerTokenSubfolders = true);同步的 PublishAsync 会忽略它,因为其调用者无论如何都会等待完整文档。

这将等待转移到客户端,在那里是有界且可见的。为小部件启用重试:

javascript
const objViewer = $('#div_ctlDoc').docViewer({
    BasePath:   'doconut',
    ResPath:    'doconut-res/images',
    retryOn409: true      // 对 202(以及旧版 409)就绪响应的重试
});

未进行 重试 的客户端会在仍在渲染的页面上显示破碎的瓦片。重试预算及其默认值(retryInitialDelayMs、retryBackoffFactor、retryMaxDelayMs、retryMaxAttempts、retryMaxTotalMs)在 查看器配置 中有文档说明。

节点间的安全性

会话绑定的令牌假设提供服务的节点看到了打开请求。在集群中并非如此,因此每会话检查会拒绝合法请求;因此集群会设置 UnsafeMode = true。

UnsafeMode = true 不是安全模型——它是一个已不再适用的模型的移除。 将其替换为签名访问票证,每个节点都可以独立验证。四个部分协同工作。

1. 在每个节点上注册票证安全。 票证受 ASP.NET Core 数据保护保护,因此每个节点必须使用相同的密钥环和应用程序名称;使用不同密钥的节点无法读取另一个节点签发的票证。

csharp
using Microsoft.AspNetCore.DataProtection;

builder.Services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(@"\\fileserver\doconut-keys"))   // 被每个节点共享
    .SetApplicationName("doconut-farm");

builder.Services.AddDoconut(options => options.UnsafeMode = true);
builder.Services.AddDoconutDistributedDocumentSecurity(options =>
{
    options.TicketLifetimeMinutes = 60;   // 默认
});

2. 在读取端检查票证。 UseDoconutDistributedDocumentSecurity() 放在读取分支的 UseDoconutCloud 之前,如 读取端示例 中所示。

3. 在文档打开时签发票证。 票证包含令牌、浏览器(通过读取端比较的 cookie)以及已登录的用户(如果有):

csharp
using System.Security.Claims;
using Microsoft.Extensions.Options;

app.MapPost("/api/open", async (string fileName, HttpContext http, FileShareConfig shareConfig,
    DistributedDocumentPublisher publisher, IDocumentAccessTicketProtector protector,
    IOptions<DistributedDocumentSecurityOptions> security, CancellationToken ct) =>
{
    var path   = Path.Combine("files", Path.GetFileName(fileName));
    var result = await publisher.PublishAsync(path, shareConfig, ct: ct);

    // 通过读取端检查的 cookie 将票据绑定到此浏览器。
    var cookieName = security.Value.BrowserCookieName;   // "doconut-client" 默认
    if (!http.Request.Cookies.TryGetValue(cookieName, out var browserId) || string.IsNullOrEmpty(browserId))
    {
        browserId = Guid.NewGuid().ToString("N");
        http.Response.Cookies.Append(cookieName, browserId, new CookieOptions
        {
            HttpOnly = true,
            Secure   = http.Request.IsHttps,
            SameSite = SameSiteMode.Lax
        });
    }

    var access = protector.Protect(new DocumentAccessTicket
    {
        Token      = result.Token,
        BrowserId  = browserId,
        UserId     = http.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "",
        ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(security.Value.TicketLifetimeMinutes),
        Nonce      = Guid.NewGuid().ToString("N")
    });

    return Results.Json(new { token = result.Token, access });
});

4. 将两者都传递给小部件。 查看器在每个请求中将票证作为 access 发送:

javascript
const resp = await fetch('/api/open?fileName=Sample.pdf', { method: 'POST' });
const { token, access } = await resp.json();
objViewer.View(token, access);

读取端会拒绝票证缺失、无效、为其他令牌签发、已过期、绑定到其他浏览器 cookie,或签发给其他已登录用户的请求。它返回 403 —— 对页面和缩略图请求返回 UnauthorizedMessage 错误图片,其他情况返回纯文本。请使用真实浏览器或保持 cookie 的客户端进行测试。

切勿将 UnsafeMode = true 带回单节点部署,也不要将其视为单节点上会话检查失败的快捷方式——在那里正确的修复是 AddSession() / UseSession()。参见 会话与安全。

关闭已发布的文档

CloseDocument(token) 在注入的 Viewer 上会释放本地会话。要从共享中移除文档的已发布工件,发布者提供:

text
bool CloseDistributedDocument(FileShareConfig fileShareConfig, string token)

使用与文档发布时相同的 FileShareConfig 进行传递。

检查清单

  1. 在一个帮助程序中构建 FileShareConfig,注册一次,并在两个部分中使用它。
  2. 将 RootPath 指向每个节点都能访问的文件夹。
  3. 使用 PublishAsync(...) 发布,或使用 EnqueueAsync(...) 进行后台发布。
  4. 在客户端调用的分支上使用 UseDoconutCloud<FileShareCloudHandler>(...) 提供服务。
  5. 在后台发布时,同时启用 FirstPagePriority 和 retryOn409,并为读取端提供一个非零的 ReadReadyPollMs。
  6. 用签名访问票据替代每会话检查——每个节点都有一个 Data Protection 密钥环,读取分支上使用 UseDoconutDistributedDocumentSecurity(),以及来自开放端点的票据——且不要单独部署 UnsafeMode = true。
  7. 通过在一个节点打开文档并从另一个节点请求后续页面来验证。

此页面对您有帮助吗?