Skip to content

Commit 11fceb8

Browse files
Merge pull request #165 from fastly/cceckman/range-err
Reject out-of-order ranges
2 parents 685fed9 + fb828c7 commit 11fceb8

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

cache/core/core.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,9 @@ func (f *Found) GetRange(from, to uint64) (io.ReadCloser, error) {
211211
if to > 0 {
212212
bopts.To(to)
213213
}
214+
if to != 0 && from > to {
215+
return nil, fmt.Errorf("GetRange from (%d) > to (%d)", from, to)
216+
}
214217

215218
body, err := f.abiEntry.Body(bopts)
216219
if err := ignoreNoneError(err); err != nil {

cache/core/core_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,57 @@ func ExampleTransaction() {
154154
panic(err)
155155
}
156156
}
157+
158+
func ExampleFound_GetRange() {
159+
const (
160+
key = "my_key"
161+
contents = "my cached object"
162+
)
163+
164+
// Start by filling the cache...
165+
w, err := core.Insert([]byte(key), core.WriteOptions{
166+
TTL: time.Hour,
167+
SurrogateKeys: []string{key},
168+
Length: uint64(len(contents)),
169+
})
170+
if err != nil {
171+
panic(err)
172+
}
173+
if _, err := io.WriteString(w, contents); err != nil {
174+
panic(err)
175+
}
176+
if err := w.Close(); err != nil {
177+
panic(err)
178+
}
179+
180+
// We get a response...
181+
f, err := core.Lookup([]byte("my_key"), core.LookupOptions{})
182+
if err != nil {
183+
panic(err)
184+
}
185+
// ...then discard the body, so we can re-open a new body reading a subset of the bytes.
186+
if err := f.Body.Close(); err != nil {
187+
panic(err)
188+
}
189+
190+
// If we try to read an invalid range (from > to), we get an error:
191+
_, err = f.GetRange(3, 1)
192+
if err == nil {
193+
panic("accepted invalid range")
194+
}
195+
196+
// We can use "0" as a signal value to say "everything to the end":
197+
body, err := f.GetRange(3, 0)
198+
if err == nil {
199+
panic("accepted invalid range")
200+
}
201+
cachedStr, err := io.ReadAll(body)
202+
if err != nil {
203+
panic(err)
204+
}
205+
if string(cachedStr) != "cached object" {
206+
panic(fmt.Sprintf("got: %q, want: %q", cachedStr, "cached object"))
207+
}
208+
209+
fmt.Printf("The cached value was: %s", cachedStr)
210+
}

0 commit comments

Comments
 (0)