mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-11-28 11:07:09 -05:00
fix(webdav): return a thumbnail in the type of the image it is made from
This commit is contained in:
1 parent
4fb37e9418
commit
ede4024ccb
11 files changed
+290
-215
No files matched your search
@@ -78,7 +78,7 @@ Announcing a type and sending it to Tika are separate settings:
|
||||
|
||||
A type that Tika takes is attempted even when it is not announced. A direct request can therefore get a preview that a listing reports as absent.
|
||||
|
||||
The thumbnail is written in the type that the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever Tika returns. The answer is the same before and after a cache hit. A Windows binary maps to `image/png` by default, because the icon Tika reads from it has transparency that a JPEG would flatten onto black.
|
||||
The thumbnail is written in the type that the **image it is made from** maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`): the file itself, or the image an extractor found in it. The icon Tika reads out of a Windows binary becomes a PNG, because a JPEG would flatten its transparency onto black, and a JPEG cover stays a JPEG. The type is kept with the cache entry, so the answer is the same before and after a cache hit.
|
||||
|
||||
#### Thumbnail Cache
|
||||
|
||||
@@ -93,6 +93,8 @@ The webdav service caches the thumbnails it generates. Choose a backend with `WE
|
||||
|
||||
`s3` needs a bucket, a region and credentials. A service other than AWS also needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT`, and it is always addressed over https. While previews are enabled, an unknown backend or an incomplete `s3` configuration fails at startup rather than running without a cache.
|
||||
|
||||
Every entry keeps the type of its image: `file` in an extended attribute (`user.oc.content_type`), `s3` as the object's `Content-Type`. A `file` cache on a filesystem without extended attributes fails at startup.
|
||||
|
||||
##### What Is Cached
|
||||
|
||||
- every generated thumbnail, one entry per size
|
||||
@@ -164,10 +166,10 @@ Three settings say what is made of what. Each one is merged onto the built-in de
|
||||
| Environment variable | Description |
|
||||
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` | Types a preview is announced and attempted for, e.g. `image/vnd.microsoft.icon` for a generator that reads icons. The webdav, graph and ocdav side all read this one name |
|
||||
| `OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES` | The type a thumbnail is returned in, per source type, as `mime:mime` entries, e.g. `image/vnd.microsoft.icon:image/png` |
|
||||
| `OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES` | The type a thumbnail is returned in, per type of the image it is made from, as `mime:mime` entries, e.g. `image/vnd.microsoft.icon:image/png` |
|
||||
| `OC_THUMBNAILS_ADDITIONAL_GENERATOR_FORMATS` | The formats the generator writes, as `mime:format` entries, e.g. `image/webp:webp`. The format is the name its own `format(...)` filter uses |
|
||||
|
||||
Reading them as a chain: a source type is mapped to the type its thumbnail is returned in, and that type is asked for by the name the generator knows it under. An icon becomes `image/png`, which the generator is asked for as `format(png)`. A type nobody mapped becomes a JPEG, and so does a mapping onto a type this service has no format name for: what a generator behind the URL really writes is its own business, and a wrong guess here must not keep the service from starting.
|
||||
Reading them as a chain: the type of the image a thumbnail is made from is mapped to the type it is returned in, and that type is asked for by the name the generator knows it under. An icon becomes `image/png`, which the generator is asked for as `format(png)`. A type nobody mapped becomes a JPEG, and so does a mapping onto a type this service has no format name for: what a generator behind the URL really writes is its own business, and a wrong guess here must not keep the service from starting.
|
||||
|
||||
The defaults return `image/png` for png, icon and windows binary sources, keep `image/gif` for a gif and return `image/jpeg` for everything else, so a client must read the response's `Content-Type` instead of assuming the type it got before.
|
||||
|
||||
|
||||
+14
-3
@@ -20,10 +20,17 @@ func DefaultFileCacheDir() string {
|
||||
return filepath.Join(defaults.BaseDataPath(), "thumbnails", "cache")
|
||||
}
|
||||
|
||||
// Image is a cached image and its type. An image without data records that a
|
||||
// file has no image.
|
||||
type Image struct {
|
||||
Data []byte
|
||||
ContentType string
|
||||
}
|
||||
|
||||
// ThumbnailCache provides cached storage for generated thumbnails.
|
||||
type ThumbnailCache interface {
|
||||
Get(key string) ([]byte, error)
|
||||
Put(key string, data []byte) error
|
||||
Get(key string) (Image, error)
|
||||
Put(key string, img Image) error
|
||||
}
|
||||
|
||||
// NewThumbnailCache creates a cache instance based on the configured backend. A
|
||||
@@ -39,7 +46,11 @@ func NewThumbnailCache(backend string, cacheDir string, s3cfg *S3CacheConfig) (T
|
||||
if dir == "" {
|
||||
dir = DefaultFileCacheDir()
|
||||
}
|
||||
return NewFileCache(dir), nil
|
||||
c := NewFileCache(dir)
|
||||
if err := c.probe(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
case "s3":
|
||||
if s3cfg == nil || !s3cfg.IsComplete() {
|
||||
return nil, errors.New("s3 thumbnail cache needs a bucket, a region and credentials")
|
||||
|
||||
+120
-99
@@ -33,52 +33,52 @@ var _ = Describe("InMemoryCache", func() {
|
||||
})
|
||||
|
||||
It("should return ErrCacheMiss for missing key", func() {
|
||||
data, err := cache.Get("nonexistent")
|
||||
got, err := cache.Get("nonexistent")
|
||||
Expect(err).To(MatchError(ErrCacheMiss))
|
||||
Expect(data).To(BeNil())
|
||||
Expect(got.Data).To(BeNil())
|
||||
})
|
||||
|
||||
It("should store and retrieve data", func() {
|
||||
err := cache.Put("key1", []byte("thumbnail-data"))
|
||||
err := cache.Put("key1", Image{Data: []byte("thumbnail-data")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("key1")
|
||||
got, err := cache.Get("key1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("thumbnail-data")))
|
||||
Expect(got.Data).To(Equal([]byte("thumbnail-data")))
|
||||
})
|
||||
|
||||
It("should return independent copies on Get", func() {
|
||||
err := cache.Put("key1", []byte("original"))
|
||||
err := cache.Put("key1", Image{Data: []byte("original")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("key1")
|
||||
got, err := cache.Get("key1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
data[0] = 'X'
|
||||
got.Data[0] = 'X'
|
||||
|
||||
original, err := cache.Get("key1")
|
||||
orig, err := cache.Get("key1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(original).To(Equal([]byte("original")))
|
||||
Expect(orig.Data).To(Equal([]byte("original")))
|
||||
})
|
||||
|
||||
It("should overwrite existing keys", func() {
|
||||
err := cache.Put("key1", []byte("v1"))
|
||||
err := cache.Put("key1", Image{Data: []byte("v1")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
err = cache.Put("key1", []byte("v2"))
|
||||
err = cache.Put("key1", Image{Data: []byte("v2")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("key1")
|
||||
got, err := cache.Get("key1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("v2")))
|
||||
Expect(got.Data).To(Equal([]byte("v2")))
|
||||
})
|
||||
|
||||
It("should handle empty data", func() {
|
||||
err := cache.Put("empty-key", []byte{})
|
||||
err := cache.Put("empty-key", Image{Data: []byte{}})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("empty-key")
|
||||
got, err := cache.Get("empty-key")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(BeEmpty())
|
||||
Expect(got.Data).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -90,21 +90,21 @@ var _ = Describe("NoopCache", func() {
|
||||
})
|
||||
|
||||
It("should always return ErrCacheMiss on Get", func() {
|
||||
data, err := cache.Get("any-key")
|
||||
got, err := cache.Get("any-key")
|
||||
Expect(err).To(MatchError(ErrCacheMiss))
|
||||
Expect(data).To(BeNil())
|
||||
Expect(got.Data).To(BeNil())
|
||||
})
|
||||
|
||||
It("should accept Put without error", func() {
|
||||
err := cache.Put("key1", []byte("data"))
|
||||
err := cache.Put("key1", Image{Data: []byte("data")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("should still miss after Put", func() {
|
||||
_ = cache.Put("key1", []byte("data"))
|
||||
data, err := cache.Get("key1")
|
||||
_ = cache.Put("key1", Image{Data: []byte("data")})
|
||||
got, err := cache.Get("key1")
|
||||
Expect(err).To(MatchError(ErrCacheMiss))
|
||||
Expect(data).To(BeNil())
|
||||
Expect(got.Data).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -113,11 +113,11 @@ var _ = Describe("NewThumbnailCache", func() {
|
||||
cache, err := NewThumbnailCache("memory", "", nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cache).ToNot(BeNil())
|
||||
err = cache.Put("k", []byte("v"))
|
||||
err = cache.Put("k", Image{Data: []byte("v")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
data, err := cache.Get("k")
|
||||
got, err := cache.Get("k")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("v")))
|
||||
Expect(got.Data).To(Equal([]byte("v")))
|
||||
})
|
||||
|
||||
It("should refuse an unknown backend", func() {
|
||||
@@ -133,9 +133,9 @@ var _ = Describe("NewThumbnailCache", func() {
|
||||
It("should create NoopCache for the 'none' backend", func() {
|
||||
cache, err := NewThumbnailCache("none", "", nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
data, err := cache.Get("k")
|
||||
got, err := cache.Get("k")
|
||||
Expect(err).To(MatchError(ErrCacheMiss))
|
||||
Expect(data).To(BeNil())
|
||||
Expect(got.Data).To(BeNil())
|
||||
})
|
||||
|
||||
It("should create S3Cache for 's3' backend with complete config", func() {
|
||||
@@ -179,12 +179,17 @@ var _ = Describe("NewThumbnailCache", func() {
|
||||
// mockS3Object is a closable reader for mock S3 objects.
|
||||
type mockS3Object struct {
|
||||
*bytes.Reader
|
||||
contentType string
|
||||
}
|
||||
|
||||
func (m *mockS3Object) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockS3Object) Stat() (minio.ObjectInfo, error) {
|
||||
return minio.ObjectInfo{ContentType: m.contentType}, nil
|
||||
}
|
||||
|
||||
var _ s3Object = (*mockS3Object)(nil)
|
||||
|
||||
// mockS3FailingObject answers the read with an error, the way minio does.
|
||||
@@ -192,8 +197,9 @@ type mockS3FailingObject struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *mockS3FailingObject) Read([]byte) (int, error) { return 0, m.err }
|
||||
func (m *mockS3FailingObject) Close() error { return nil }
|
||||
func (m *mockS3FailingObject) Read([]byte) (int, error) { return 0, m.err }
|
||||
func (m *mockS3FailingObject) Close() error { return nil }
|
||||
func (m *mockS3FailingObject) Stat() (minio.ObjectInfo, error) { return minio.ObjectInfo{}, m.err }
|
||||
|
||||
var _ s3Object = (*mockS3FailingObject)(nil)
|
||||
|
||||
@@ -229,7 +235,7 @@ func (m *mockS3Client) GetObject(_ context.Context, _, objectName string, _ mini
|
||||
StatusCode: http.StatusNotFound,
|
||||
}}, nil
|
||||
}
|
||||
return &mockS3Object{Reader: bytes.NewReader(data)}, nil
|
||||
return &mockS3Object{Reader: bytes.NewReader(data), contentType: m.contentTypes[objectName]}, nil
|
||||
}
|
||||
|
||||
func (m *mockS3Client) PutObject(_ context.Context, _, objectName string, reader io.Reader, _ int64, opts minio.PutObjectOptions) (minio.UploadInfo, error) {
|
||||
@@ -267,77 +273,77 @@ var _ = Describe("S3Cache", func() {
|
||||
})
|
||||
|
||||
It("should return ErrCacheMiss for missing key", func() {
|
||||
data, err := cache.Get("nonexistent-key")
|
||||
got, err := cache.Get("nonexistent-key")
|
||||
Expect(err).To(MatchError(ErrCacheMiss))
|
||||
Expect(data).To(BeNil())
|
||||
Expect(got.Data).To(BeNil())
|
||||
})
|
||||
|
||||
It("should store and retrieve data", func() {
|
||||
err := cache.Put("sha256:abc123-400x400.jpg", []byte("thumbnail-data"))
|
||||
err := cache.Put("sha256:abc123-400x400.jpg", Image{Data: []byte("thumbnail-data")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("sha256:abc123-400x400.jpg")
|
||||
got, err := cache.Get("sha256:abc123-400x400.jpg")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("thumbnail-data")))
|
||||
Expect(got.Data).To(Equal([]byte("thumbnail-data")))
|
||||
})
|
||||
|
||||
It("should return independent copies on Get", func() {
|
||||
err := cache.Put("key1", []byte("original"))
|
||||
err := cache.Put("key1", Image{Data: []byte("original")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("key1")
|
||||
got, err := cache.Get("key1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
data[0] = 'X'
|
||||
got.Data[0] = 'X'
|
||||
|
||||
original, err := cache.Get("key1")
|
||||
orig, err := cache.Get("key1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(original).To(Equal([]byte("original")))
|
||||
Expect(orig.Data).To(Equal([]byte("original")))
|
||||
})
|
||||
|
||||
It("should overwrite existing keys", func() {
|
||||
err := cache.Put("key1", []byte("v1"))
|
||||
err := cache.Put("key1", Image{Data: []byte("v1")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
err = cache.Put("key1", []byte("v2"))
|
||||
err = cache.Put("key1", Image{Data: []byte("v2")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("key1")
|
||||
got, err := cache.Get("key1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("v2")))
|
||||
Expect(got.Data).To(Equal([]byte("v2")))
|
||||
})
|
||||
|
||||
It("should handle empty data", func() {
|
||||
err := cache.Put("empty-key", []byte{})
|
||||
err := cache.Put("empty-key", Image{Data: []byte{}})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("empty-key")
|
||||
got, err := cache.Get("empty-key")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(BeEmpty())
|
||||
Expect(got.Data).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("should use flat key format", func() {
|
||||
key := "sha256:abc123-400x400.jpg"
|
||||
err := cache.Put(key, []byte("data"))
|
||||
err := cache.Put(key, Image{Data: []byte("data")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get(key)
|
||||
got, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("data")))
|
||||
Expect(got.Data).To(Equal([]byte("data")))
|
||||
})
|
||||
|
||||
It("should initialize client lazily on first access", func() {
|
||||
Expect(cache.client).To(BeNil())
|
||||
|
||||
_ = cache.Put("key1", []byte("data"))
|
||||
_ = cache.Put("key1", Image{Data: []byte("data")})
|
||||
Expect(cache.client).ToNot(BeNil())
|
||||
})
|
||||
|
||||
It("should handle S3 errors gracefully on Get", func() {
|
||||
mockClient.getErr = errors.New("connection refused")
|
||||
|
||||
data, err := cache.Get("any-key")
|
||||
got, err := cache.Get("any-key")
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(data).To(BeNil())
|
||||
Expect(got.Data).To(BeNil())
|
||||
})
|
||||
|
||||
It("should keep an error that is not a missing key an error", func() {
|
||||
@@ -351,7 +357,7 @@ var _ = Describe("S3Cache", func() {
|
||||
It("should handle S3 errors gracefully on Put", func() {
|
||||
mockClient.putErr = errors.New("connection refused")
|
||||
|
||||
err := cache.Put("key1", []byte("data"))
|
||||
err := cache.Put("key1", Image{Data: []byte("data")})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
|
||||
@@ -360,27 +366,18 @@ var _ = Describe("S3Cache", func() {
|
||||
return nil, errors.New("init failed")
|
||||
}
|
||||
|
||||
data, err := cache.Get("any-key")
|
||||
got, err := cache.Get("any-key")
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(data).To(BeNil())
|
||||
Expect(got.Data).To(BeNil())
|
||||
})
|
||||
|
||||
It("should derive Content-Type from .jpg extension", func() {
|
||||
err := cache.Put("sha256:abc123-400x400.jpg", []byte("data"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mockClient.contentTypes["sha256:abc123-400x400.jpg"]).To(Equal("image/jpeg"))
|
||||
})
|
||||
It("stores the entry's type as the object's Content-Type", func() {
|
||||
Expect(cache.Put("key1", Image{Data: []byte("data"), ContentType: "image/png"})).To(Succeed())
|
||||
Expect(mockClient.contentTypes["key1"]).To(Equal("image/png"))
|
||||
|
||||
It("should derive Content-Type from .png extension", func() {
|
||||
err := cache.Put("sha256:def456-800x600.png", []byte("data"))
|
||||
got, err := cache.Get("key1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mockClient.contentTypes["sha256:def456-800x600.png"]).To(Equal("image/png"))
|
||||
})
|
||||
|
||||
It("should fallback to application/octet-stream for unknown extension", func() {
|
||||
err := cache.Put("key-without-ext", []byte("data"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mockClient.contentTypes["key-without-ext"]).To(Equal("application/octet-stream"))
|
||||
Expect(got.ContentType).To(Equal("image/png"))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -403,24 +400,24 @@ var _ = Describe("FileCache", func() {
|
||||
})
|
||||
|
||||
It("should return ErrCacheMiss for missing key", func() {
|
||||
data, err := cache.Get("ab/cd/ef1234567890/400x400.jpg")
|
||||
got, err := cache.Get("ab/cd/ef1234567890/400x400.jpg")
|
||||
Expect(err).To(MatchError(ErrCacheMiss))
|
||||
Expect(data).To(BeNil())
|
||||
Expect(got.Data).To(BeNil())
|
||||
})
|
||||
|
||||
It("should store and retrieve data", func() {
|
||||
key := "ab/cd/ef1234567890/400x400.jpg"
|
||||
err := cache.Put(key, []byte("thumbnail-data"))
|
||||
err := cache.Put(key, Image{Data: []byte("thumbnail-data")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get(key)
|
||||
got, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("thumbnail-data")))
|
||||
Expect(got.Data).To(Equal([]byte("thumbnail-data")))
|
||||
})
|
||||
|
||||
It("should use hierarchical directory layout", func() {
|
||||
key := "ab/cd/ef1234567890/400x400.jpg"
|
||||
err := cache.Put(key, []byte("thumbnail-data"))
|
||||
err := cache.Put(key, Image{Data: []byte("thumbnail-data")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
expectedPath := filepath.Join(tmpdir, "ab", "cd", "ef1234567890", "400x400.jpg")
|
||||
@@ -431,7 +428,7 @@ var _ = Describe("FileCache", func() {
|
||||
|
||||
It("should create parent directories with 0700 permissions", func() {
|
||||
key := "ab/cd/ef1234567890/400x400.jpg"
|
||||
err := cache.Put(key, []byte("thumbnail-data"))
|
||||
err := cache.Put(key, Image{Data: []byte("thumbnail-data")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
dirPath := filepath.Join(tmpdir, "ab", "cd")
|
||||
@@ -443,36 +440,36 @@ var _ = Describe("FileCache", func() {
|
||||
|
||||
It("should return independent copies on Get", func() {
|
||||
key := "ab/cd/ef1234567890/400x400.jpg"
|
||||
err := cache.Put(key, []byte("original"))
|
||||
err := cache.Put(key, Image{Data: []byte("original")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get(key)
|
||||
got, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
data[0] = 'X'
|
||||
got.Data[0] = 'X'
|
||||
|
||||
original, err := cache.Get(key)
|
||||
orig, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(original).To(Equal([]byte("original")))
|
||||
Expect(orig.Data).To(Equal([]byte("original")))
|
||||
})
|
||||
|
||||
It("should overwrite existing keys", func() {
|
||||
key := "ab/cd/ef1234567890/400x400.jpg"
|
||||
Expect(cache.Put(key, []byte("v1"))).To(Succeed())
|
||||
Expect(cache.Put(key, []byte("v2"))).To(Succeed())
|
||||
Expect(cache.Put(key, Image{Data: []byte("v1")})).To(Succeed())
|
||||
Expect(cache.Put(key, Image{Data: []byte("v2")})).To(Succeed())
|
||||
|
||||
data, err := cache.Get(key)
|
||||
got, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("v2")), "a key whose value can change has to be replaceable")
|
||||
Expect(got.Data).To(Equal([]byte("v2")), "a key whose value can change has to be replaceable")
|
||||
})
|
||||
|
||||
It("should handle empty data", func() {
|
||||
key := "ab/cd/ef1234567890/400x400.jpg"
|
||||
err := cache.Put(key, []byte{})
|
||||
err := cache.Put(key, Image{Data: []byte{}})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get(key)
|
||||
got, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(BeEmpty())
|
||||
Expect(got.Data).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("should use atomic write via temp file + rename", func() {
|
||||
@@ -500,14 +497,14 @@ var _ = Describe("FileCache", func() {
|
||||
}
|
||||
}()
|
||||
|
||||
err := cache.Put(key, bytes.Repeat([]byte("x"), 1024*1024))
|
||||
err := cache.Put(key, Image{Data: bytes.Repeat([]byte("x"), 1024*1024)})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
close(done)
|
||||
|
||||
data, err := cache.Get(key)
|
||||
got, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(len(data)).To(Equal(1024 * 1024))
|
||||
Expect(len(got.Data)).To(Equal(1024 * 1024))
|
||||
_ = sawTempFile
|
||||
})
|
||||
|
||||
@@ -518,10 +515,24 @@ var _ = Describe("FileCache", func() {
|
||||
// The cache dir path passes through a regular file, so MkdirAll cannot
|
||||
// create the target directory for any user (root or not) -> Put must error.
|
||||
rc := NewFileCache(filepath.Join(blocker, "sub"))
|
||||
err := rc.Put("ab/cd/ef1234567890/400x400.jpg", []byte("data"))
|
||||
err := rc.Put("ab/cd/ef1234567890/400x400.jpg", Image{Data: []byte("data")})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
|
||||
It("keeps the content type in an extended attribute", func() {
|
||||
key := "ab/cd/ef1234567890/400x400"
|
||||
Expect(cache.Put(key, Image{Data: []byte("thumbnail-data"), ContentType: "image/png"})).To(Succeed())
|
||||
|
||||
got, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got.ContentType).To(Equal("image/png"))
|
||||
Expect(got.Data).To(Equal([]byte("thumbnail-data")), "the file holds nothing but the image")
|
||||
|
||||
raw, err := os.ReadFile(filepath.Join(tmpdir, key))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(raw).To(Equal([]byte("thumbnail-data")))
|
||||
})
|
||||
|
||||
It("should handle corrupt/partial files on Get", func() {
|
||||
key := "ab/cd/ef1234567890/400x400.jpg"
|
||||
dirPath := filepath.Join(tmpdir, "ab", "cd", "ef1234567890")
|
||||
@@ -530,9 +541,9 @@ var _ = Describe("FileCache", func() {
|
||||
filePath := filepath.Join(dirPath, "400x400.jpg")
|
||||
Expect(os.WriteFile(filePath, []byte("corrupt-data"), 0600)).To(Succeed())
|
||||
|
||||
data, err := cache.Get(key)
|
||||
got, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("corrupt-data")))
|
||||
Expect(got.Data).To(Equal([]byte("corrupt-data")))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -549,21 +560,31 @@ var _ = Describe("NewThumbnailCache factory", func() {
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(fileCache.dir).To(Equal(tmpdir))
|
||||
|
||||
err = cache.Put("ab/cd/ef1234567890/400x400.jpg", []byte("file-data"))
|
||||
err = cache.Put("ab/cd/ef1234567890/400x400.jpg", Image{Data: []byte("file-data")})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := cache.Get("ab/cd/ef1234567890/400x400.jpg")
|
||||
got, err := cache.Get("ab/cd/ef1234567890/400x400.jpg")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("file-data")))
|
||||
Expect(got.Data).To(Equal([]byte("file-data")))
|
||||
})
|
||||
|
||||
It("should create FileCache with default dir when empty string passed", func() {
|
||||
GinkgoT().Setenv("OC_BASE_DATA_PATH", GinkgoT().TempDir())
|
||||
|
||||
cache, err := NewThumbnailCache("file", "", nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
fileCache, ok := cache.(*FileCache)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(fileCache.dir).To(Equal(DefaultFileCacheDir()))
|
||||
})
|
||||
|
||||
It("refuses a directory it cannot write to at startup", func() {
|
||||
blocker := filepath.Join(GinkgoT().TempDir(), "blocker")
|
||||
Expect(os.WriteFile(blocker, []byte("x"), 0600)).To(Succeed())
|
||||
|
||||
_, err := NewThumbnailCache("file", filepath.Join(blocker, "sub"), nil)
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("S3CacheConfig validation", func() {
|
||||
|
||||
+57
-14
@@ -2,11 +2,17 @@ package cache
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/pkg/xattr"
|
||||
)
|
||||
|
||||
const contentTypeAttr = "user.oc.content_type"
|
||||
|
||||
// FileCache stores thumbnails on the local filesystem using hierarchical directories.
|
||||
type FileCache struct {
|
||||
dir string
|
||||
@@ -16,23 +22,52 @@ func NewFileCache(dir string) *FileCache {
|
||||
return &FileCache{dir: dir}
|
||||
}
|
||||
|
||||
// The cache key is already a hierarchical relative path, so the on-disk
|
||||
// location is the cache dir joined with it.
|
||||
func (c *FileCache) Get(key string) ([]byte, error) {
|
||||
path := filepath.Join(c.dir, key)
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, ErrCacheMiss
|
||||
}
|
||||
return nil, err
|
||||
// probe fails when the filesystem cannot keep the content type next to the bytes.
|
||||
func (c *FileCache) probe() error {
|
||||
if err := os.MkdirAll(c.dir, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return data, nil
|
||||
f, err := os.CreateTemp(c.dir, "tmpprobe")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
defer f.Close()
|
||||
|
||||
if err := xattr.FSet(f, contentTypeAttr, []byte("image/png")); err != nil {
|
||||
return fmt.Errorf("the thumbnail cache in %s needs a filesystem with extended attributes, use another directory or the s3 or memory backend: %w", c.dir, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *FileCache) Put(key string, data []byte) error {
|
||||
// The cache key is already a hierarchical relative path, so the on-disk
|
||||
// location is the cache dir joined with it.
|
||||
func (c *FileCache) Get(key string) (Image, error) {
|
||||
f, err := os.Open(filepath.Join(c.dir, key))
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return Image{}, ErrCacheMiss
|
||||
}
|
||||
return Image{}, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
data, err := io.ReadAll(f)
|
||||
if err != nil {
|
||||
return Image{}, err
|
||||
}
|
||||
|
||||
contentType, err := xattr.FGet(f, contentTypeAttr)
|
||||
if err != nil && !errors.Is(err, xattr.ENOATTR) {
|
||||
return Image{}, err
|
||||
}
|
||||
|
||||
return Image{Data: data, ContentType: string(contentType)}, nil
|
||||
}
|
||||
|
||||
func (c *FileCache) Put(key string, img Image) error {
|
||||
imgPath := filepath.Join(c.dir, key)
|
||||
dir := filepath.Dir(imgPath)
|
||||
|
||||
@@ -46,12 +81,20 @@ func (c *FileCache) Put(key string, data []byte) error {
|
||||
}
|
||||
tempPath := f.Name()
|
||||
|
||||
if _, err := f.Write(data); err != nil {
|
||||
if _, err := f.Write(img.Data); err != nil {
|
||||
f.Close()
|
||||
os.Remove(tempPath)
|
||||
return err
|
||||
}
|
||||
|
||||
if img.ContentType != "" {
|
||||
if err := xattr.FSet(f, contentTypeAttr, []byte(img.ContentType)); err != nil {
|
||||
f.Close()
|
||||
os.Remove(tempPath)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
os.Remove(tempPath)
|
||||
|
||||
+15
-15
@@ -11,7 +11,7 @@ const InMemoryCacheMaxBytes = 128 << 20
|
||||
// InMemoryCacheMaxBytes and evicting in insertion order.
|
||||
type InMemoryCache struct {
|
||||
mu sync.RWMutex
|
||||
data map[string][]byte
|
||||
data map[string]Image
|
||||
order []string
|
||||
size int
|
||||
maxSize int
|
||||
@@ -19,45 +19,45 @@ type InMemoryCache struct {
|
||||
|
||||
func NewInMemoryCache() *InMemoryCache {
|
||||
return &InMemoryCache{
|
||||
data: make(map[string][]byte),
|
||||
data: make(map[string]Image),
|
||||
maxSize: InMemoryCacheMaxBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *InMemoryCache) Get(key string) ([]byte, error) {
|
||||
func (c *InMemoryCache) Get(key string) (Image, error) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
data, ok := c.data[key]
|
||||
img, ok := c.data[key]
|
||||
if !ok {
|
||||
return nil, ErrCacheMiss
|
||||
return Image{}, ErrCacheMiss
|
||||
}
|
||||
|
||||
result := make([]byte, len(data))
|
||||
copy(result, data)
|
||||
return result, nil
|
||||
data := make([]byte, len(img.Data))
|
||||
copy(data, img.Data)
|
||||
return Image{Data: data, ContentType: img.ContentType}, nil
|
||||
}
|
||||
|
||||
func (c *InMemoryCache) Put(key string, data []byte) error {
|
||||
func (c *InMemoryCache) Put(key string, img Image) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
cp := make([]byte, len(data))
|
||||
copy(cp, data)
|
||||
data := make([]byte, len(img.Data))
|
||||
copy(data, img.Data)
|
||||
|
||||
if old, ok := c.data[key]; ok {
|
||||
c.size -= len(old)
|
||||
c.size -= len(old.Data)
|
||||
} else {
|
||||
c.order = append(c.order, key)
|
||||
}
|
||||
c.data[key] = cp
|
||||
c.size += len(cp)
|
||||
c.data[key] = Image{Data: data, ContentType: img.ContentType}
|
||||
c.size += len(data)
|
||||
|
||||
// the entry just written stays, even when it is larger than the budget
|
||||
for c.size > c.maxSize && len(c.order) > 1 {
|
||||
oldest := c.order[0]
|
||||
c.order = c.order[1:]
|
||||
c.size -= len(c.data[oldest])
|
||||
c.size -= len(c.data[oldest].Data)
|
||||
delete(c.data, oldest)
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -3,10 +3,10 @@ package cache
|
||||
// NoopCache always returns a cache miss and discards puts.
|
||||
type NoopCache struct{}
|
||||
|
||||
func (NoopCache) Get(_ string) ([]byte, error) {
|
||||
return nil, ErrCacheMiss
|
||||
func (NoopCache) Get(_ string) (Image, error) {
|
||||
return Image{}, ErrCacheMiss
|
||||
}
|
||||
|
||||
func (NoopCache) Put(_ string, _ []byte) error {
|
||||
func (NoopCache) Put(_ string, _ Image) error {
|
||||
return nil
|
||||
}
|
||||
+16
-18
@@ -4,9 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
@@ -30,6 +28,7 @@ func (c S3CacheConfig) IsComplete() bool {
|
||||
// s3Object is the subset of minio.Object used by S3Cache.
|
||||
type s3Object interface {
|
||||
io.ReadCloser
|
||||
Stat() (minio.ObjectInfo, error)
|
||||
}
|
||||
|
||||
// s3Client is the subset of minio.Client used by S3Cache.
|
||||
@@ -85,23 +84,28 @@ func (c *S3Cache) initClient() error {
|
||||
return c.initErr
|
||||
}
|
||||
|
||||
func (c *S3Cache) Get(key string) ([]byte, error) {
|
||||
func (c *S3Cache) Get(key string) (Image, error) {
|
||||
if err := c.initClient(); err != nil {
|
||||
return nil, err
|
||||
return Image{}, err
|
||||
}
|
||||
|
||||
obj, err := c.client.GetObject(context.Background(), c.config.Bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, asCacheError(err)
|
||||
return Image{}, asCacheError(err)
|
||||
}
|
||||
defer obj.Close()
|
||||
|
||||
data, err := io.ReadAll(obj)
|
||||
info, err := obj.Stat()
|
||||
if err != nil {
|
||||
return nil, asCacheError(err)
|
||||
return Image{}, asCacheError(err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
data, err := io.ReadAll(obj)
|
||||
if err != nil {
|
||||
return Image{}, asCacheError(err)
|
||||
}
|
||||
|
||||
return Image{Data: data, ContentType: info.ContentType}, nil
|
||||
}
|
||||
|
||||
// asCacheError reports a missing object as a cache miss. minio's GetObject only
|
||||
@@ -121,25 +125,19 @@ func asCacheError(err error) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *S3Cache) Put(key string, data []byte) error {
|
||||
func (c *S3Cache) Put(key string, img Image) error {
|
||||
if err := c.initClient(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ext := filepath.Ext(key)
|
||||
contentType := mime.TypeByExtension(ext)
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
|
||||
_, err := c.client.PutObject(
|
||||
context.Background(),
|
||||
c.config.Bucket,
|
||||
key,
|
||||
bytes.NewReader(data),
|
||||
int64(len(data)),
|
||||
bytes.NewReader(img.Data),
|
||||
int64(len(img.Data)),
|
||||
minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
ContentType: img.ContentType,
|
||||
},
|
||||
)
|
||||
return err
|
||||
|
||||
@@ -6,13 +6,11 @@ import (
|
||||
"github.com/opencloud-eu/opencloud/services/webdav/pkg/generator"
|
||||
)
|
||||
|
||||
// DefaultTypeMapping answers for every type in DefaultSourceTypes, so the
|
||||
// type a thumbnail is returned in can be read off here instead of being
|
||||
// guessed from a file name. Types that carry alpha or animation keep their own
|
||||
// format, everything else becomes a JPEG. An icon is the one type no generator
|
||||
// writes back: it has to become a PNG, or JPEG would flatten its transparent
|
||||
// pixels onto black. A windows binary is in the list for the same reason,
|
||||
// although it is no image type itself: what Tika extracts from it is its icon.
|
||||
// DefaultTypeMapping maps the type of the image a thumbnail is made from, the
|
||||
// file itself or what an extractor found in it. Types that carry alpha or
|
||||
// animation keep their own format, everything else becomes a JPEG. An icon is
|
||||
// the one type no generator writes back: it has to become a PNG, or JPEG would
|
||||
// flatten its transparent pixels onto black.
|
||||
var DefaultTypeMapping = []string{
|
||||
"image/png:image/png",
|
||||
"image/gif:image/gif",
|
||||
@@ -24,13 +22,6 @@ var DefaultTypeMapping = []string{
|
||||
"image/tiff:image/jpeg",
|
||||
"image/vnd.microsoft.icon:image/png",
|
||||
"image/x-icon:image/png",
|
||||
"application/x-msdownload:image/png",
|
||||
"text/plain:image/jpeg",
|
||||
"audio/flac:image/jpeg",
|
||||
"audio/mpeg:image/jpeg",
|
||||
"audio/ogg:image/jpeg",
|
||||
"application/vnd.geogebra.slides:image/jpeg",
|
||||
"application/vnd.geogebra.pinboard:image/jpeg",
|
||||
}
|
||||
|
||||
// TypeMapping says which type a thumbnail of an image is returned in, for the
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package thumbnail_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
|
||||
@@ -11,9 +13,11 @@ import (
|
||||
var _ = Describe("TypeMapping", func() {
|
||||
m := thumbnail.NewTypeMapping(nil)
|
||||
|
||||
It("answers for every type a preview is made of", func() {
|
||||
It("answers for every image type a preview is made of", func() {
|
||||
for _, mimeType := range thumbnail.NewSourceTypes(nil).List() {
|
||||
Expect(m.TargetFor(mimeType)).ToNot(BeEmpty(), "%s has no output type", mimeType)
|
||||
if strings.HasPrefix(mimeType, "image/") {
|
||||
Expect(m.TargetFor(mimeType)).ToNot(BeEmpty(), "%s has no output type", mimeType)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -27,8 +31,9 @@ var _ = Describe("TypeMapping", func() {
|
||||
Expect(m.TargetFor("image/x-icon")).To(Equal("image/png"))
|
||||
})
|
||||
|
||||
It("writes the icon of a windows binary as a png", func() {
|
||||
Expect(m.TargetFor("application/x-msdownload")).To(Equal("image/png"))
|
||||
It("maps no file type that is not an image, the image made of it decides", func() {
|
||||
Expect(m.TargetFor("application/x-msdownload")).To(BeEmpty())
|
||||
Expect(m.TargetFor("audio/mpeg")).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("reads a type with parameters", func() {
|
||||
|
||||
@@ -123,9 +123,11 @@ func fileIsProcessing(info *providerv1beta1.ResourceInfo) bool {
|
||||
return utils.ReadPlainFromOpaque(info.GetOpaque(), "status") == "processing"
|
||||
}
|
||||
|
||||
// thumbnailStorageKey is <prefix>/wxh-<operation>.format, with the snapped box as size.
|
||||
func thumbnailStorageKey(checksum, mimeType string, w, h int, format, operation string) string {
|
||||
return storageKeyPrefix(checksum, mimeType) + "/" + fmt.Sprintf("%dx%d-%s.%s", w, h, operation, format)
|
||||
// thumbnailStorageKey is <prefix>/wxh-<operation>, with the snapped box as size.
|
||||
// The output type depends on the extracted image, so it is stored with the
|
||||
// entry, not part of the key.
|
||||
func thumbnailStorageKey(checksum, mimeType string, w, h int, operation string) string {
|
||||
return storageKeyPrefix(checksum, mimeType) + "/" + fmt.Sprintf("%dx%d-%s", w, h, operation)
|
||||
}
|
||||
|
||||
// sourceStorageKey holds the extracted image for all sizes; empty means the file has none.
|
||||
@@ -432,14 +434,6 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R
|
||||
}
|
||||
mimeType := info.GetMimeType()
|
||||
|
||||
// The thumbnail is returned in the type the source type maps to, asked for
|
||||
// by the name the generator's filter uses. What an extractor hands on is
|
||||
// re-encoded to that type, because the request has to decide it: a cache
|
||||
// hit knows the key, not the bytes. Keeping a png cover a png needs the
|
||||
// embedded type before the key is built, which is what the preview presence
|
||||
// work puts into the file's metadata.
|
||||
outputType, outputFormat := w.outputFor(mimeType)
|
||||
|
||||
// The operation is resolved up front so it can be part of the cache key: a
|
||||
// fill and a fit-in request with the same dimensions produce different images
|
||||
// and must not share a cache entry. noUpscale reports whether the generator
|
||||
@@ -458,13 +452,15 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R
|
||||
// requests that produce the same image share one entry and the number of
|
||||
// entries per file stays bounded by the ladder. It needs nothing but the
|
||||
// request, so a hit still returns without touching storage.
|
||||
cacheKey := thumbnailStorageKey(checksum, mimeType, box.Dx(), box.Dy(), outputFormat, operation)
|
||||
cacheKey := thumbnailStorageKey(checksum, mimeType, box.Dx(), box.Dy(), operation)
|
||||
|
||||
if w.cache != nil {
|
||||
cached, err := w.cache.Get(cacheKey)
|
||||
switch {
|
||||
case err == nil && cached.ContentType != "":
|
||||
return Thumbnail{Data: cached.Data, ContentType: cached.ContentType}, nil
|
||||
case err == nil:
|
||||
return Thumbnail{Data: cached, ContentType: outputType}, nil
|
||||
// written without a type, e.g. copied without its xattrs: made again
|
||||
case !errors.Is(err, cache.ErrCacheMiss):
|
||||
// a miss is the normal answer; anything else is the cache itself
|
||||
// failing, and the thumbnail is made again without a word otherwise
|
||||
@@ -488,6 +484,9 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
// the thumbnail keeps the type of the image it is made from, or what that maps to
|
||||
outputType, outputFormat := w.outputFor(srcType)
|
||||
|
||||
// webdav snaps the requested size onto a configured resolution and lets the
|
||||
// generator fill that box. Only fit-in suppresses upscaling (noUpscale); for
|
||||
// fill/thumbnail/resize the generator may enlarge a small source (e.g. a text
|
||||
@@ -509,7 +508,7 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R
|
||||
}
|
||||
|
||||
if w.cache != nil {
|
||||
if err := w.cache.Put(cacheKey, thumbBytes); err != nil {
|
||||
if err := w.cache.Put(cacheKey, cache.Image{Data: thumbBytes, ContentType: outputType}); err != nil {
|
||||
logger.Debug().Err(err).Msg("could not cache thumbnail")
|
||||
}
|
||||
}
|
||||
@@ -546,13 +545,12 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta
|
||||
if converter != nil && w.cache != nil {
|
||||
sourceKey = sourceStorageKey(checksum, mimeType, converter.Name())
|
||||
if cached, err := w.cache.Get(sourceKey); err == nil {
|
||||
if len(cached) == 0 {
|
||||
if len(cached.Data) == 0 {
|
||||
return nil, "", nil, ErrNoThumbnail
|
||||
}
|
||||
|
||||
//the cache holds bytes, so the type comes from them: the generator
|
||||
//sniffs them too, this only tells it what to expect
|
||||
return bytes.NewReader(cached), http.DetectContentType(cached), func() {}, nil
|
||||
if cached.ContentType != "" {
|
||||
return bytes.NewReader(cached.Data), cached.ContentType, func() {}, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -575,14 +573,14 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta
|
||||
if errors.Is(err, preprocessor.ErrNoThumbnail) {
|
||||
//the file carries no image, which is an answer and worth remembering;
|
||||
//a failed extraction is not, it may succeed on the next try
|
||||
w.rememberSource(sourceKey, nil)
|
||||
w.rememberSource(sourceKey, cache.Image{})
|
||||
return nil, "", nil, ErrNoThumbnail
|
||||
}
|
||||
if err != nil || img == nil {
|
||||
logger.Debug().Err(err).Msg("could not convert file to image")
|
||||
return nil, "", nil, fmt.Errorf("%w: could not get image", ErrNotFound)
|
||||
}
|
||||
w.rememberSource(sourceKey, img.Data)
|
||||
w.rememberSource(sourceKey, cache.Image{Data: img.Data, ContentType: img.ContentType})
|
||||
|
||||
return bytes.NewReader(img.Data), img.ContentType, func() {}, nil
|
||||
}
|
||||
@@ -596,11 +594,11 @@ const maxCachedSourceBytes = 8 << 20
|
||||
// rememberSource keeps what an extractor made of a file, or the empty entry
|
||||
// that says it made nothing. An image too large to keep is simply not kept:
|
||||
// the extraction runs again next time, which costs time, not correctness.
|
||||
func (w *ThumbnailWorkflow) rememberSource(key string, data []byte) {
|
||||
if w.cache == nil || len(data) > maxCachedSourceBytes {
|
||||
func (w *ThumbnailWorkflow) rememberSource(key string, img cache.Image) {
|
||||
if w.cache == nil || len(img.Data) > maxCachedSourceBytes {
|
||||
return
|
||||
}
|
||||
_ = w.cache.Put(key, data)
|
||||
_ = w.cache.Put(key, img)
|
||||
}
|
||||
|
||||
// supportsMimeType reports whether a preview is attempted for the type: the
|
||||
|
||||
@@ -383,9 +383,10 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Expect(data).To(Equal(thumbBytes))
|
||||
Expect(contentType).To(Equal("image/jpeg"))
|
||||
|
||||
cached, err := testCache.Get(thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/jpeg", 128, 128, "jpg", "fill"))
|
||||
cached, err := testCache.Get(thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/jpeg", 128, 128, "fill"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cached).To(Equal(thumbBytes))
|
||||
Expect(cached.Data).To(Equal(thumbBytes))
|
||||
Expect(cached.ContentType).To(Equal("image/jpeg"))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -848,13 +849,14 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
|
||||
cached, err := testCache.Get(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cached).To(Equal(captured.data), "the cover art is kept as the source, not per size")
|
||||
Expect(cached.Data).To(Equal(captured.data), "the cover art is kept as the source, not per size")
|
||||
Expect(cached.ContentType).To(HavePrefix("image/"), "with the type the extractor named")
|
||||
})
|
||||
|
||||
It("sends the kept source instead of extracting a second time", func() {
|
||||
pngBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "noise.png"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), pngBytes)).To(Succeed())
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), cache.Image{Data: pngBytes, ContentType: "image/png"})).To(Succeed())
|
||||
|
||||
//the file itself is not an mp3: extracting it would fail, so what
|
||||
//reaches the generator can only come from the cache
|
||||
@@ -873,7 +875,7 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
})
|
||||
|
||||
It("asks once for a file that carries nothing, whatever size follows", func() {
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), nil)).To(Succeed())
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), cache.Image{})).To(Succeed())
|
||||
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3"))
|
||||
|
||||
@@ -888,12 +890,12 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Expect(err).To(MatchError(ErrNoThumbnail))
|
||||
Expect(captured.data).To(BeEmpty(), "the generator is not asked at all")
|
||||
|
||||
_, err = testCache.Get(thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", 256, 256, "jpg", "fill"))
|
||||
_, err = testCache.Get(thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", 256, 256, "fill"))
|
||||
Expect(err).To(MatchError(cache.ErrCacheMiss), "only the source entry says there is nothing")
|
||||
})
|
||||
|
||||
It("does not take another extractor's empty answer", func() {
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "tika"), nil)).To(Succeed())
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "tika"), cache.Image{})).To(Succeed())
|
||||
|
||||
mp3Bytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "empty.mp3"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
@@ -924,10 +926,12 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Height: 64,
|
||||
}
|
||||
|
||||
_, err = wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
result, err := wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(captured.data).ToNot(BeEmpty())
|
||||
Expect(captured.data).ToNot(Equal(ggsBytes))
|
||||
Expect(captured.path).To(ContainSubstring("format(png)"), "the embedded thumbnail is a png and stays one")
|
||||
Expect(result.ContentType).To(Equal("image/png"))
|
||||
})
|
||||
|
||||
It("renders text files to an image", func() {
|
||||
@@ -1003,18 +1007,19 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Expect(captured.path).To(ContainSubstring(wantFilter))
|
||||
Expect(contentType).To(Equal(wantType))
|
||||
|
||||
_, err = testCache.Get(wantKey)
|
||||
Expect(err).ToNot(HaveOccurred(), "the format belongs in the cache key")
|
||||
cached, err := testCache.Get(wantKey)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cached.ContentType).To(Equal(wantType), "the type is kept with the entry")
|
||||
},
|
||||
Entry("a png keeps its alpha channel",
|
||||
"image/png", "img.png", "smart/filters:format(png)", "image/png",
|
||||
thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "image/png", 64, 64, "png", "fill")),
|
||||
thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "image/png", 64, 64, "fill")),
|
||||
Entry("a gif keeps its animation",
|
||||
"image/gif", "anim.gif", "filters:format(gif)", "image/gif",
|
||||
thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "image/gif", 64, 64, "gif", "stretch")),
|
||||
thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "image/gif", 64, 64, "stretch")),
|
||||
Entry("a bmp becomes a jpeg",
|
||||
"image/bmp", "scan.bmp", "smart/filters:format(jpg)", "image/jpeg",
|
||||
thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "image/bmp", 64, 64, "jpg", "fill")),
|
||||
thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "image/bmp", 64, 64, "fill")),
|
||||
)
|
||||
|
||||
It("follows a configured chain into a format the built-in generator cannot write", func() {
|
||||
@@ -1058,7 +1063,7 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Describe("cache hit shortcut", func() {
|
||||
It("should return cached thumbnail without calling generator or downloading the file", func() {
|
||||
cachedThumb := []byte("cached-thumbnail")
|
||||
err := testCache.Put(thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/jpeg", 128, 128, "jpg", "fill"), cachedThumb)
|
||||
err := testCache.Put(thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/jpeg", 128, 128, "fill"), cache.Image{Data: cachedThumb, ContentType: "image/png"})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
// No download expectations are set up. If the workflow tried to
|
||||
@@ -1074,7 +1079,7 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
data, contentType := result.Data, result.ContentType
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal(cachedThumb))
|
||||
Expect(contentType).To(Equal("image/jpeg"))
|
||||
Expect(contentType).To(Equal("image/png"), "the type stored with the entry, not one derived from the file")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1345,9 +1350,10 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Expect(data).To(Equal(thumbBytes))
|
||||
Expect(contentType).To(Equal("image/jpeg"))
|
||||
|
||||
cached, err := testCache.Get(thumbnailStorageKey("5ba1b086d95a7e0fd8ff4323caee0c412ab07fc3", "image/jpeg", 64, 64, "jpg", "fill"))
|
||||
cached, err := testCache.Get(thumbnailStorageKey("5ba1b086d95a7e0fd8ff4323caee0c412ab07fc3", "image/jpeg", 64, 64, "fill"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cached).To(Equal(thumbBytes))
|
||||
Expect(cached.Data).To(Equal(thumbBytes))
|
||||
Expect(cached.ContentType).To(Equal("image/jpeg"))
|
||||
})
|
||||
|
||||
It("should handle pre-signed public links with signature and expiration", func() {
|
||||
@@ -1768,7 +1774,7 @@ var _ = Describe("storage keys", func() {
|
||||
|
||||
It("files a thumbnail and its source under one prefix", func() {
|
||||
source := sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef", "tika")
|
||||
thumb := thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef", 64, 64, "jpg", "fill")
|
||||
thumb := thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef", 64, 64, "fill")
|
||||
Expect(path.Dir(thumb)).To(Equal(path.Dir(source)))
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user