ImageSharp.Web
Description
This issue is designed to capture the architecture and tasks required to build an extensible library for parsing URL API instructions and caching the result.
Feel free to discuss below. We'll assign specific issues for functional components as we determine them.
Basic Requirements
- [x] Asp.NET Core Middleware to capture valid requests
- [x] Extensible configuration for Caching, ImageServices, and Processing. Must be secure.
- [x]
IImageServiceimplementations for physical file system and remote images. - [x]
IDistributedCacheimplementation for physical file system that can be switched out for Redis, Azure, etc. How do we handle cleanup, Response codes? - [x] Fast, low collision hashing of URL for cache implementations.
Pipeline
The following gives an overall summary of the image processing pipeline.
- Request is intercepted by Middleware (Authorisation?)
IImageServiceis assigned using URL prefix pattern matching (Regex?)IImageServicedetermines validity of request and attempts to return stream containing image.IDistributedCacheimplementation checks if file exists. (Redirect if exists?)- Not cached? URL querystring params are parsed for matching processor.
- Image is processed by matches via fluent API.
- Result is cached and image served.
- Cleanup of expired cached files. (How?, When?)
Edit
Updated Requirements and Pipeline below
Basic Requirements
- [x] Asp.NET Core Middleware to capture valid requests
- [x] Extensible configuration for Parsing, Resolving, Processing, and Caching. Must be secure
- [ ] Configuration for handling EXIF metadata
- [x]
IUriParserimplementation for parsing URI requests for command string that can be switched out - [x]
IImageResolverimplementation collection for physical file system that - [x] Extensible
CommandParserimplementation for converting commands into real values for processing. - [x]
IImageWebProcessorfor Resize - [ ]
IImageWebProcessorfor Quality - [x]
IImageWebProcessorfor Format - [ ]
IImageWebProcessorfor BackgroundColor - [x]
IImageCacheimplementation for physical file system that can be switched out for Azure, etc. - [x] Fast, low collision hashing of URL for cache implementations
- [x]
ILoggerbased logging - [ ]
TagHelperfor generatingimg,picturemarkup
Pipeline
The following gives an overall summary of the image processing pipeline.
- Request is intercepted by Middleware
IUriParserextracts commands; if not found, exitIImageResolveris assigned usingMatch()methodIImageResolverdetermines validity of request and attempts to return stream containing image.IImageCacheimplementation checks if file exists. (Returns correct response)- Not cached? URL querystring params are parsed for matching processor.
IImageWebProcessorimplementations process the image- Result is cached and image served.
- Authorization afaik shouldn't be ImageSharp's concern. You would plug in your authorization middleware before the ImageSharp.Web one and that would be responsible for handling anything authz-wise.
Authorization afaik shouldn't be ImageSharp's concern. You would plug in your authorization middleware before the ImageSharp.Web one and that would be responsible for handling anything authz-wise.
Great! I thought/hoped it would be the case.
Just adding this here for anyone wanting to get started: https://gist.github.com/clausjensen/bce60ccad6d65a92eadb4ea77229b287
@clausjensen I've actually started writing some code. Baby steps though.
https://github.com/JimBobSquarePants/ImageSharp/tree/e4d3aedb33af44bf8b384fa6a277b31bbfb2a381/src/ImageSharp.Web
Aaah awesome :) I didn't know how far you were on the basic middleware stuff but looks like you're already ahead of that!
What about multi-tenancy and access restrictions to specific set's\folders of images? for example: products that are not "live" yet only admins are allowed to access the images
@KLuuKer That would still not be the responsibility of ImageSharp.Web - that would be something you handle in your authorization middleware. ImageSharp should simply be responsible for handling requests that have already passed through any authorization middleware that may/may not allow the request to continue being handled.
@clausjensen i can live with that
but allow to give prefixes or something for the cache keys, for multi-tenancy isolation (using the same cache)
@KLuuKer actually I think it may be a good idea to create a whole other issue just to talk about the multi tenancy stuff, as I'm pretty certain there's a lot of things in regards to how caching should/could be done and how caching can best be configured for these kind of setups.
I'm a bit worried notes and ideas like these may get lost if not separated out into an issue focused just on this part. Unfortunately it is not something I know that much about so I suspect there's a lot of potential pitfalls here we might as well get addressed to begin with. ( @JimBobSquarePants ?)
@clausjensen @KLuuKer I'll set up issues for each item later tonight.
Re caching, that's what IDistributedCache is for. Want multitenancy, switch to Azure caching or another implementation.
I think a good place to start in designing the middleware is to determine what the inputs to the middleware would be and how those come into the request (query string, headers, etc). Also what are the possible operations (is it just for resizing or are there other processing operations supported?)
It would be great if the mapping between the inputs and how they make it to the middleware was configurable so that people can use whatever routing or conventions they want and the image middleware would handle the heavy lifting.
For example, some inputs for resizing could be:
- Width - this would likely come from the url
- Height - this would likely come from the url
- Quality - this would likely come from the url
- Format - this could come from an accept header on the request
- Focal Point - this would likely come from the url
Are there any existing image services or plugins that have functionality you would like to incorporate? Are there any standards around such services?
Coming up with some sample scenarios like:
/images?w=100&h=250&q=.8 /images/100/250/.8
and walking through how the request would flow would be a great exercise. Also including caching and authentication/authorization in these scenarios will help spell out how those pieces interact.
Another big consideration in the design is making sure the response is property formatted to be consumed by a CDN. It is great to support IDistrubutedCache but ultimately CDNs are the best and most common way to cache images.
- IImageService is assigned using URL prefix pattern matching (Regex?)
Should IImageService interface something like Task<bool> ShouldProcessAsync(HttpContext context)
so the IImageService is responsible for its own implementation of URL matching.
On step 5 (Not cached? URL querystring params are parsed for matching processor.) either there is a global parser that fills some kind of ResizeParameter Dictionary or again each IImageService get what he needs from the Request. It would be a solution to implement different resizing parameter conventions (headers, querystring, path…)
I think a global IImageServiceParameterProvider could be helpful to separate well the IImageService from its parameters needs.
If so the Task<bool> ShouldProcessAsync(HttpContext context) would become something like Task<bool> ShouldProcessAsync(IImageServiceParameterProvider provider) ???
Another consideration: it would be helpfull to design the IImageServices in a chaining fashion… We could then imagine something like : AzureStoreImageService => ImageManipulationService
This case Task<Stream> ResolveImageAsync(HttpContext context, string path) is maybe not the best interface for it…
It could maybe also help to make preventive imageservice like : PreventDdoSAttackImageService => ImageManipulationService
@lfoust
It would be great if the mapping between the inputs and how they make it to the middleware was configurable so that people can use whatever routing or conventions they want and the image middleware would handle the heavy lifting.
That feels to me like opening a can of worms. I would stick with a single unified URL Querystring API with identifiers for IImageService implementations using a prefix.
e.g. http://mysite.com/remote/http://remote-image.jpg?width=200 would resolve to the RemoteImageService since we are using the remote prefix.
If an IImageService had an empty prefix e.g. PhysicalFileImageService it would match all image requests containing recognized querystring parameters. Any implementations like this would be a last resort and only called when there are no prefix matching services.
All the inputs you mentioned would come from the Querystring API
width=200height=100quality=75format=pngxy=20&xy=50(This is the standard method to pass arrays through qs params, though very verbose)
Note IMO It's better to use more descriptive parameters as we would support more processors as plugins.
There are no standards around this as far as I'm aware.
Another big consideration in the design is making sure the response is property formatted to be consumed by a CDN. It is great to support IDistrubutedCache but ultimately CDNs are the best and most common way to cache images.
Exactly. My thought would be that use the file system IDistrubutedCache for smaller sites but if you want scaling you would use an Azure or Amazon based implementations (This is something I would probably build privately and sell licenses for - Gotta earn something from my years or work!). Those caches would be installed on a custom endpoint that the CDN will request if no matching image is found on their system.
@romain-preston
Each IImageService should definitely have something like Task<bool> ShouldProcessAsync(HttpContext context) though I think we would have already split the request URL into different parts for processing so would pass them to the method.
On Step 5. Each installed processor would accept and parse the querystring NameValueCollection and return a result accordingly. All instruction sets are querystring only. Every CDN I know allows caching by querystring params.
Another consideration: it would be helpfull to design the IImageServices in a chaining fashion… We could then imagine something like : AzureStoreImageService => ImageManipulationService
I don't see any benefit in this. Each service is responsible for matching a pattern and returning an image. Chaining would only add overheads and complexity.
Have a look at the current codebase. I've defined some of the interfaces and a rough guide in code + comments of the pipeline. I'm gonna need help working out the new HttpContext.Request/Response parts sorted + writing tests, creating a test website etc.
https://github.com/JimBobSquarePants/ImageSharp/tree/dotweb/src/ImageSharp.Web
@JimBobSquarePants , i see, now it makes more sense seeing the IImageWebProcessor implementation !
I'll check if i can give you a hand in the next days now that the system is almost settled.
@JimBobSquarePants been checking out out the code, and it's a good start 👍 Personally there's a few things I would probably design differently, but that may just be my preference as opposed to actually better!
The main thing that I would change is the way the services are created. They are currently all added on the ImageSharpMiddlewareOptions object in the UseImageSharp call. That seems like it limits you quite a lot, and means you have to pass IHostingEnvironment etc in all the APIs.
I would add these into the DI container so that you can use DI throughout instead. Then you would have an AddImageSharpMiddleware() extension method to register all the defaults, and users can easily plugin their own implementations using DI. You can obviously register the default implementations as singletons, so shouldn't be any performance differences. This is the biggest change I'd make, and it's more in-line with standard ASP.NET Core approaches. I can knock up a PR to discuss if you like 🙂
On other things: the Commands infrastructure looks cool, but the URL/querystring matching design is very opinionated, potentially too much? I personally like the idea of essentially having a service for extracting the required parameters width=200, height=100 etc, rather than forcing them to be querystrings. For example I might want to use routing values: /resize/{width}/{height}/{path} for example.
But yeah, looking good 🙂 I've got a blog post I started as a follow up the caching one, storing files in the wwwroot which seems pretty close to what we're doing here (though less extensible). I'll try and get it finished off soon, and see if there's anything in there that's applicable here!
@andrewlock Thanks for having a look. Your feedback is fantastic I really, really appreciate it. 👍
Soooo.. I've implemented some changes.
First I stripped out all that IHostingEnvironment parameters. The environment is now passed through DI when I add the services. Much cleaner!
Users can implement their own implementations and configure them using the following overload in Startup (Use non-generic for default).
public void ConfigureServices(IServiceCollection services)
{
services.UseImageSharpServices<MyCustomImageSharpConfiguration>();
}
Secondly I created something called an IUriParser that looks like this.
/// <summary>
/// Defines a contract for parsing commands from URI's
/// </summary>
public interface IUriParser
{
/// <summary>
/// Returns a collection of commands from the current request
/// </summary>
/// <param name="context">Encapsulates all HTTP-specific information about an individual HTTP request</param>
/// <returns>The <see cref="IDictionary{TKey,TValue}"/></returns>
IDictionary<string, string> ParseUriCommands(HttpContext context);
}
This allows you to create your own dictionary of commands from the request so if you chose to. /resize/{width}/{height}/{path} would be a possible. Personally I would always use querystring params though since they're dead easy to parse.
It's looking pretty clean and it runs smoothly. 😄
There's still tests, a couple of built in processors, custom events to add and some 404 handling but I'm very happy with it all now.
Looking forward to any further feedback.
p.s. Your blog was invaluable today. I learnt an absolute ton about config reading through it. 🍻
Agree with @andrewlock on the points mentioned. There's also some limitations to what you have available when configuring (without injecting weird things around in places they shouldn't be and jumping through hoops) if you don't go with this route - so whether or not it's a personal preference (and mine too) .. I believe it's actually also the most appropriate way of initializing it 😃
Very nice work so far @JimBobSquarePants
@clausjensen The config stuff took me most of the day to set up, BIG learning curve! :neckbeard: I think other devs should be able to configure it pretty easily in the future though though setting up their own configuration classes which is simple enough. Always open to suggestions though
@JimBobSquarePants That sounds much more conventional, glad to be of use! 😄 The IUriParser sounds spot on 👍 I'll have another play this afternoon and check out your handwork - top marks for turn around! 😄