|
| 1 | +using System.Buffers; |
| 2 | +using System.Text; |
| 3 | +using System.Text.Json; |
| 4 | +using Imazen.Abstractions.Blobs; |
| 5 | +using Imazen.Abstractions.Resulting; |
| 6 | +using Imazen.Routing.HttpAbstractions; |
| 7 | +using Imazen.Routing.Layers; |
| 8 | +using Imazen.Routing.Promises; |
| 9 | +using Imazen.Routing.Requests; |
| 10 | + |
| 11 | +namespace Imageflow.Server.ExampleModernAPI; |
| 12 | + |
| 13 | + |
| 14 | +internal record CustomFileData(string Path1, string QueryString1, string Path2, string QueryString2); |
| 15 | + |
| 16 | +/// <summary> |
| 17 | +/// This layer will capture requests for .json.custom paths. No .custom file actually exists, but the .json does, and we'll use that to determine the dependencies. |
| 18 | +/// </summary> |
| 19 | +public class CustomMediaLayer(PathMapper jsonFileMapper) : Imazen.Routing.Layers.IRoutingLayer |
| 20 | +{ |
| 21 | + public string Name => ".json.custom file handler"; |
| 22 | + |
| 23 | + public IFastCond? FastPreconditions => Conditions.HasPathSuffixOrdinalIgnoreCase(".json.custom"); |
| 24 | + public ValueTask<CodeResult<IRoutingEndpoint>?> ApplyRouting(MutableRequest request, CancellationToken cancellationToken = default) |
| 25 | + { |
| 26 | + // FastPreconditions should have already been checked |
| 27 | + var result = jsonFileMapper.TryMapVirtualPath(request.Path.Replace(".json.custom", ".json")); |
| 28 | + if (result == null) |
| 29 | + { |
| 30 | + // no mapping found |
| 31 | + return new ValueTask<CodeResult<IRoutingEndpoint>?>((CodeResult<IRoutingEndpoint>?)null); |
| 32 | + } |
| 33 | + var physicalPath = result.Value.MappedPhysicalPath; |
| 34 | + var lastWriteTimeUtc = File.GetLastWriteTimeUtc(physicalPath); |
| 35 | + if (lastWriteTimeUtc.Year == 1601) // file doesn't exist, pass to next middleware |
| 36 | + { |
| 37 | + return new ValueTask<CodeResult<IRoutingEndpoint>?>((CodeResult<IRoutingEndpoint>?)null); |
| 38 | + } |
| 39 | + // Ok, the file exists. We can load and parse it using System.Text.Json to determine the dependencies.\ |
| 40 | + return RouteFromJsonFile(physicalPath, lastWriteTimeUtc, result.Value.MappingUsed, request, cancellationToken); |
| 41 | + } |
| 42 | + |
| 43 | + private async ValueTask<CodeResult<IRoutingEndpoint>?> RouteFromJsonFile(string jsonFilePath, DateTime lastWriteTimeUtc, IPathMapping mappingUsed, MutableRequest request, CancellationToken cancellationToken) |
| 44 | + { |
| 45 | + // TODO: here, we could cache the json files in memory using a key based on jsonFilePath and lastWriteTimeUtc. |
| 46 | + |
| 47 | + var jsonText = await File.ReadAllTextAsync(jsonFilePath, cancellationToken); |
| 48 | + var data = JsonSerializer.Deserialize<CustomFileData>(jsonText); |
| 49 | + if (data == null) |
| 50 | + { |
| 51 | + return CodeResult<IRoutingEndpoint>.Err((HttpStatus.ServerError, "Failed to parse .json custom data file")); |
| 52 | + } |
| 53 | + |
| 54 | + return new PromiseWrappingEndpoint(new CustomMediaPromise(request.ToSnapshot(true),data)); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +internal class CustomMediaPromise(IRequestSnapshot r, CustomFileData data) : ICacheableBlobPromise |
| 59 | +{ |
| 60 | + public bool IsCacheSupporting => true; |
| 61 | + public IRequestSnapshot FinalRequest { get; } = r; |
| 62 | + |
| 63 | + public async ValueTask<IAdaptableHttpResponse> CreateResponseAsync(IRequestSnapshot request, IBlobRequestRouter router, IBlobPromisePipeline pipeline, |
| 64 | + CancellationToken cancellationToken = default) |
| 65 | + { |
| 66 | + // This code path isn't called, it's just to satisfy the primitive IInstantPromise interface. |
| 67 | + return new BlobResponse(await TryGetBlobAsync(request, router, pipeline, cancellationToken)); |
| 68 | + } |
| 69 | + |
| 70 | + public bool HasDependencies => true; |
| 71 | + public bool ReadyToWriteCacheKeyBasisData { get; private set; } |
| 72 | + |
| 73 | + /// <summary> |
| 74 | + /// Gets a promise for the given path that includes caching logic if indicated by the caching configuration and the latency by default. |
| 75 | + /// </summary> |
| 76 | + /// <param name="router"></param> |
| 77 | + /// <param name="childRequestUri"></param> |
| 78 | + /// <param name="cancellationToken"></param> |
| 79 | + /// <returns></returns> |
| 80 | + private async ValueTask<CodeResult<ICacheableBlobPromise>> RouteDependencyAsync(IBlobRequestRouter router, string childRequestUri, |
| 81 | + CancellationToken cancellationToken = default) |
| 82 | + { |
| 83 | + if (FinalRequest.OriginatingRequest == null) |
| 84 | + { |
| 85 | + return CodeResult<ICacheableBlobPromise>.ErrFrom(HttpStatus.BadRequest, "OriginatingRequest is required, but was null"); |
| 86 | + } |
| 87 | + var dependencyRequest = MutableRequest.ChildRequest(FinalRequest.OriginatingRequest, FinalRequest, childRequestUri, HttpMethods.Get); |
| 88 | + var routingResult = await router.RouteToPromiseAsync(dependencyRequest, cancellationToken); |
| 89 | + if (routingResult == null) |
| 90 | + { |
| 91 | + return CodeResult<ICacheableBlobPromise>.ErrFrom(HttpStatus.NotFound, "Dependency not found: " + childRequestUri); |
| 92 | + } |
| 93 | + if (routingResult.TryUnwrapError(out var error)) |
| 94 | + { |
| 95 | + return CodeResult<ICacheableBlobPromise>.Err(error.WithAppend("Error routing to dependency: " + childRequestUri)); |
| 96 | + } |
| 97 | + return CodeResult<ICacheableBlobPromise>.Ok(routingResult.Unwrap()); |
| 98 | + } |
| 99 | + public async ValueTask<CodeResult> RouteDependenciesAsync(IBlobRequestRouter router, CancellationToken cancellationToken = default) |
| 100 | + { |
| 101 | + var uri1 = data.Path1 + data.QueryString1; |
| 102 | + var uri2 = data.Path2 + data.QueryString2; |
| 103 | + |
| 104 | + foreach (var uri in new[]{uri1, uri2}) |
| 105 | + { |
| 106 | + var routingResult = await RouteDependencyAsync(router, uri, cancellationToken); |
| 107 | + if (routingResult.TryUnwrapError(out var error)) |
| 108 | + { |
| 109 | + return CodeResult.Err(error); |
| 110 | + } |
| 111 | + Dependencies ??= new List<ICacheableBlobPromise>(); |
| 112 | + Dependencies.Add(routingResult.Unwrap()); |
| 113 | + } |
| 114 | + ReadyToWriteCacheKeyBasisData = true; |
| 115 | + return CodeResult.Ok(); |
| 116 | + } |
| 117 | + |
| 118 | + internal List<ICacheableBlobPromise>? Dependencies { get; private set; } |
| 119 | + |
| 120 | + private LatencyTrackingZone? latencyZone = null; |
| 121 | + /// <summary> |
| 122 | + /// Must route dependencies first! |
| 123 | + /// </summary> |
| 124 | + public LatencyTrackingZone? LatencyZone { |
| 125 | + get |
| 126 | + { |
| 127 | + if (!ReadyToWriteCacheKeyBasisData) throw new InvalidOperationException("Dependencies must be routed first"); |
| 128 | + // produce a latency zone based on all dependency strings, joined, plus the sum of their latency defaults |
| 129 | + if (latencyZone != null) return latencyZone; |
| 130 | + var latency = 0; |
| 131 | + var sb = new StringBuilder(); |
| 132 | + sb.Append("customMediaSwitcher("); |
| 133 | + foreach (var dependency in Dependencies!) |
| 134 | + { |
| 135 | + latency += dependency.LatencyZone?.DefaultMs ?? 0; |
| 136 | + sb.Append(dependency.LatencyZone?.TrackingZone ?? "(unknown)"); |
| 137 | + } |
| 138 | + sb.Append(")"); |
| 139 | + latencyZone = new LatencyTrackingZone(sb.ToString(), latency, true); //AlwaysShield is true (never skip caching) |
| 140 | + return latencyZone; |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + public void WriteCacheKeyBasisPairsToRecursive(IBufferWriter<byte> writer) |
| 145 | + { |
| 146 | + FinalRequest.WriteCacheKeyBasisPairsTo(writer); |
| 147 | + if (Dependencies == null) throw new InvalidOperationException("Dependencies must be routed first"); |
| 148 | + foreach (var dependency in Dependencies) |
| 149 | + { |
| 150 | + dependency.WriteCacheKeyBasisPairsToRecursive(writer); |
| 151 | + } |
| 152 | + |
| 153 | + var otherCacheKeyData = 1; |
| 154 | + writer.WriteInt(otherCacheKeyData); |
| 155 | + } |
| 156 | + |
| 157 | + private byte[]? cacheKey32Bytes = null; |
| 158 | + public byte[] GetCacheKey32Bytes() |
| 159 | + { |
| 160 | + return cacheKey32Bytes ??= this.GetCacheKey32BytesUncached(); |
| 161 | + } |
| 162 | + |
| 163 | + public bool SupportsPreSignedUrls => false; |
| 164 | + |
| 165 | + public async ValueTask<CodeResult<IBlobWrapper>> TryGetBlobAsync(IRequestSnapshot request, IBlobRequestRouter router, IBlobPromisePipeline pipeline, |
| 166 | + CancellationToken cancellationToken = default) |
| 167 | + { |
| 168 | + // Our logic is to return whichever dependency is smaller. |
| 169 | + // This is a contrived example, but it's a good example of how to use dependencies. |
| 170 | + var blobWrappers = new List<IBlobWrapper>(); |
| 171 | + var smallestBlob = default(IBlobWrapper); |
| 172 | + try |
| 173 | + { |
| 174 | + foreach (var dependency in Dependencies!) |
| 175 | + { |
| 176 | + var result = await dependency.TryGetBlobAsync(request, router, pipeline, cancellationToken); |
| 177 | + if (result.TryUnwrapError(out var error)) |
| 178 | + { |
| 179 | + return CodeResult<IBlobWrapper>.Err(error); |
| 180 | + } |
| 181 | + var blob = result.Unwrap(); |
| 182 | + blobWrappers.Add(blob); |
| 183 | + |
| 184 | + if (smallestBlob == null || blob.Attributes.EstimatedBlobByteCount < smallestBlob.Attributes.EstimatedBlobByteCount) |
| 185 | + { |
| 186 | + smallestBlob = blob; |
| 187 | + } |
| 188 | + } |
| 189 | + if (smallestBlob == null) |
| 190 | + { |
| 191 | + return CodeResult<IBlobWrapper>.ErrFrom(HttpStatus.NotFound, "No dependencies found"); |
| 192 | + } |
| 193 | + return CodeResult<IBlobWrapper>.Ok(smallestBlob.ForkReference()); |
| 194 | + } |
| 195 | + finally |
| 196 | + { |
| 197 | + foreach (var blobWrapper in blobWrappers) |
| 198 | + { |
| 199 | + blobWrapper.Dispose(); |
| 200 | + } |
| 201 | + } |
| 202 | + } |
| 203 | +} |
| 204 | + |
0 commit comments