StatumResource.vala 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using Invercargill;
  2. using Invercargill.DataStructures;
  3. using Astralis;
  4. namespace Statum {
  5. /**
  6. * A precompressed, named resource served from the Statum resource endpoint
  7. * (`/_statum/resource/{name}`).
  8. *
  9. * Mirrors the old Spry 0.1 `StaticResource` (removed in Spry 0.2): each
  10. * concrete resource exposes
  11. * the encodings it was precompressed with (identity/gzip/zstd/br), an ETag
  12. * per encoding, and the ability to render itself as an {@link HttpResult}.
  13. */
  14. public interface StatumResource : Object {
  15. /** The name the resource is served under (the `{name}` path segment). */
  16. public abstract string name { get; }
  17. /**
  18. * Selects the best supported encoding for a request given the set of
  19. * `Accept-Encoding` values the client advertised.
  20. */
  21. public abstract string get_best_encoding(Set<string> supported);
  22. /** The ETag to send for a given encoding. */
  23. public abstract string get_etag_for(string encoding);
  24. /** Renders the resource for the given encoding as an {@link HttpResult}. */
  25. public abstract HttpResult to_result(string encoding, StatusCode status = StatusCode.OK) throws GLib.Error;
  26. }
  27. /**
  28. * A {@link StatumResource} whose bytes are baked in at compile time.
  29. *
  30. * Concrete subclasses (typically generated by `statum-mkres`) provide the
  31. * precompressed byte arrays and the abstract metadata/encoding members; this
  32. * base supplies the {@link get_etag_for}/{@link to_result} implementation.
  33. */
  34. public abstract class ConstantStatumResource : Object, StatumResource {
  35. public abstract string name { get; }
  36. public abstract string file_hash { get; }
  37. public abstract string content_type { get; }
  38. public abstract string get_best_encoding(Set<string> supported);
  39. public abstract unowned uint8[] get_encoding(string encoding);
  40. public string get_etag_for(string encoding) {
  41. return @"\"$encoding-$file_hash\"";
  42. }
  43. public HttpResult to_result(string encoding, StatusCode status = StatusCode.OK) throws GLib.Error {
  44. var result = new HttpDataResult(Wrap.byte_array(get_encoding(encoding)), status);
  45. result.set_header("Content-Type", content_type);
  46. result.set_header("Content-Encoding", encoding);
  47. result.set_header("ETag", get_etag_for(encoding));
  48. return result;
  49. }
  50. }
  51. }