Debian Codegraph @

plumbing/format/packfile/delta_selector.go

raw
1 package packfile
2
3 import (
4 "sort"
5 "sync"
6
7 "github.com/go-git/go-git/v5/plumbing"
8 "github.com/go-git/go-git/v5/plumbing/storer"
9 )
10
11 const (
12 // deltas based on deltas, how many steps we can do.
13 // 50 is the default value used in JGit
14 maxDepth = int64(50)
15 )
16
17 // applyDelta is the set of object types that we should apply deltas
18 var applyDelta = map[plumbing.ObjectType]bool{
19 plumbing.BlobObject: true,
20 plumbing.TreeObject: true,
21 }
22
23 type deltaSelector struct {
24 storer storer.EncodedObjectStorer
25 }
26
27 func newDeltaSelector(s storer.EncodedObjectStorer) *deltaSelector {
28 return &deltaSelector{s}
29 }
30
31 // ObjectsToPack creates a list of ObjectToPack from the hashes
32 // provided, creating deltas if it's suitable, using an specific
33 // internal logic. `packWindow` specifies the size of the sliding
34 // window used to compare objects for delta compression; 0 turns off
35 // delta compression entirely.
36 func (dw *deltaSelector) ObjectsToPack(
37 hashes []plumbing.Hash,
38 packWindow uint,
39 ) ([]*ObjectToPack, error) {
40 otp, err := dw.objectsToPack(hashes, packWindow)
41 if err != nil {
42 return nil, err
43 }
44
45 if packWindow == 0 {
46 return otp, nil
47 }
48
49 dw.sort(otp)
50
51 var objectGroups [][]*ObjectToPack
52 var prev *ObjectToPack
53 i := -1
54 for _, obj := range otp {
55 if prev == nil || prev.Type() != obj.Type() {
56 objectGroups = append(objectGroups, []*ObjectToPack{obj})
57 i++
58 prev = obj
59 } else {
60 objectGroups[i] = append(objectGroups[i], obj)
61 }
62 }
63
64 var wg sync.WaitGroup
65 var once sync.Once
66 for _, objs := range objectGroups {
67 objs := objs
68 wg.Add(1)
69 go func() {
70 if walkErr := dw.walk(objs, packWindow); walkErr != nil {
71 once.Do(func() {
72 err = walkErr
73 })
74 }
75 wg.Done()
76 }()
77 }
78 wg.Wait()
79
80 if err != nil {
81 return nil, err
82 }
83
84 return otp, nil
85 }
86
87 func (dw *deltaSelector) objectsToPack(
88 hashes []plumbing.Hash,
89 packWindow uint,
90 ) ([]*ObjectToPack, error) {
91 var objectsToPack []*ObjectToPack
92 for _, h := range hashes {
93 var o plumbing.EncodedObject
94 var err error
95 if packWindow == 0 {
96 o, err = dw.encodedObject(h)
97 } else {
98 o, err = dw.encodedDeltaObject(h)
99 }
100 if err != nil {
101 return nil, err
102 }
103
104 otp := newObjectToPack(o)
105 if _, ok := o.(plumbing.DeltaObject); ok {
106 otp.CleanOriginal()
107 }
108
109 objectsToPack = append(objectsToPack, otp)
110 }
111
112 if packWindow == 0 {
113 return objectsToPack, nil
114 }
115
116 if err := dw.fixAndBreakChains(objectsToPack); err != nil {
117 return nil, err
118 }
119
120 return objectsToPack, nil
121 }
122
123 func (dw *deltaSelector) encodedDeltaObject(h plumbing.Hash) (plumbing.EncodedObject, error) {
124 edos, ok := dw.storer.(storer.DeltaObjectStorer)
125 if !ok {
126 return dw.encodedObject(h)
127 }
128
129 return edos.DeltaObject(plumbing.AnyObject, h)
130 }
131
132 func (dw *deltaSelector) encodedObject(h plumbing.Hash) (plumbing.EncodedObject, error) {
133 return dw.storer.EncodedObject(plumbing.AnyObject, h)
134 }
135
136 func (dw *deltaSelector) fixAndBreakChains(objectsToPack []*ObjectToPack) error {
137 m := make(map[plumbing.Hash]*ObjectToPack, len(objectsToPack))
138 for _, otp := range objectsToPack {
139 m[otp.Hash()] = otp
140 }
141
142 for _, otp := range objectsToPack {
143 if err := dw.fixAndBreakChainsOne(m, otp); err != nil {
144 return err
145 }
146 }
147
148 return nil
149 }
150
151 func (dw *deltaSelector) fixAndBreakChainsOne(objectsToPack map[plumbing.Hash]*ObjectToPack, otp *ObjectToPack) error {
152 if !otp.Object.Type().IsDelta() {
153 return nil
154 }
155
156 // Initial ObjectToPack instances might have a delta assigned to Object
157 // but no actual base initially. Once Base is assigned to a delta, it means
158 // we already fixed it.
159 if otp.Base != nil {
160 return nil
161 }
162
163 do, ok := otp.Object.(plumbing.DeltaObject)
164 if !ok {
165 // if this is not a DeltaObject, then we cannot retrieve its base,
166 // so we have to break the delta chain here.
167 return dw.undeltify(otp)
168 }
169
170 base, ok := objectsToPack[do.BaseHash()]
171 if !ok {
172 // The base of the delta is not in our list of objects to pack, so
173 // we break the chain.
174 return dw.undeltify(otp)
175 }
176
177 if err := dw.fixAndBreakChainsOne(objectsToPack, base); err != nil {
178 return err
179 }
180
181 otp.SetDelta(base, otp.Object)
182 return nil
183 }
184
185 func (dw *deltaSelector) restoreOriginal(otp *ObjectToPack) error {
186 if otp.Original != nil {
187 return nil
188 }
189
190 if !otp.Object.Type().IsDelta() {
191 return nil
192 }
193
194 obj, err := dw.encodedObject(otp.Hash())
195 if err != nil {
196 return err
197 }
198
199 otp.SetOriginal(obj)
200
201 return nil
202 }
203
204 // undeltify undeltifies an *ObjectToPack by retrieving the original object from
205 // the storer and resetting it.
206 func (dw *deltaSelector) undeltify(otp *ObjectToPack) error {
207 if err := dw.restoreOriginal(otp); err != nil {
208 return err
209 }
210
211 otp.Object = otp.Original
212 otp.Depth = 0
213 return nil
214 }
215
216 func (dw *deltaSelector) sort(objectsToPack []*ObjectToPack) {
217 sort.Sort(byTypeAndSize(objectsToPack))
218 }
219
220 func (dw *deltaSelector) walk(
221 objectsToPack []*ObjectToPack,
222 packWindow uint,
223 ) error {
224 indexMap := make(map[plumbing.Hash]*deltaIndex)
225 for i := 0; i < len(objectsToPack); i++ {
226 // Clean up the index map and reconstructed delta objects for anything
227 // outside our pack window, to save memory.
228 if i > int(packWindow) {
229 obj := objectsToPack[i-int(packWindow)]
230
231 delete(indexMap, obj.Hash())
232
233 if obj.IsDelta() {
234 obj.SaveOriginalMetadata()
235 obj.CleanOriginal()
236 }
237 }
238
239 target := objectsToPack[i]
240
241 // If we already have a delta, we don't try to find a new one for this
242 // object. This happens when a delta is set to be reused from an existing
243 // packfile.
244 if target.IsDelta() {
245 continue
246 }
247
248 // We only want to create deltas from specific types.
249 if !applyDelta[target.Type()] {
250 continue
251 }
252
253 for j := i - 1; j >= 0 && i-j < int(packWindow); j-- {
254 base := objectsToPack[j]
255 // Objects must use only the same type as their delta base.
256 // Since objectsToPack is sorted by type and size, once we find
257 // a different type, we know we won't find more of them.
258 if base.Type() != target.Type() {
259 break
260 }
261
262 if err := dw.tryToDeltify(indexMap, base, target); err != nil {
263 return err
264 }
265 }
266 }
267
268 return nil
269 }
270
271 func (dw *deltaSelector) tryToDeltify(indexMap map[plumbing.Hash]*deltaIndex, base, target *ObjectToPack) error {
272 // Original object might not be present if we're reusing a delta, so we
273 // ensure it is restored.
274 if err := dw.restoreOriginal(target); err != nil {
275 return err
276 }
277
278 if err := dw.restoreOriginal(base); err != nil {
279 return err
280 }
281
282 // If the sizes are radically different, this is a bad pairing.
283 if target.Size() < base.Size()>>4 {
284 return nil
285 }
286
287 msz := dw.deltaSizeLimit(
288 target.Object.Size(),
289 base.Depth,
290 target.Depth,
291 target.IsDelta(),
292 )
293
294 // Nearly impossible to fit useful delta.
295 if msz <= 8 {
296 return nil
297 }
298
299 // If we have to insert a lot to make this work, find another.
300 if base.Size()-target.Size() > msz {
301 return nil
302 }
303
304 if _, ok := indexMap[base.Hash()]; !ok {
305 indexMap[base.Hash()] = new(deltaIndex)
306 }
307
308 // Now we can generate the delta using originals
309 delta, err := getDelta(indexMap[base.Hash()], base.Original, target.Original)
310 if err != nil {
311 return err
312 }
313
314 // if delta better than target
315 if delta.Size() < msz {
316 target.SetDelta(base, delta)
317 }
318
319 return nil
320 }
321
322 func (dw *deltaSelector) deltaSizeLimit(targetSize int64, baseDepth int,
323 targetDepth int, targetDelta bool) int64 {
324 if !targetDelta {
325 // Any delta should be no more than 50% of the original size
326 // (for text files deflate of whole form should shrink 50%).
327 n := targetSize >> 1
328
329 // Evenly distribute delta size limits over allowed depth.
330 // If src is non-delta (depth = 0), delta <= 50% of original.
331 // If src is almost at limit (9/10), delta <= 10% of original.
332 return n * (maxDepth - int64(baseDepth)) / maxDepth
333 }
334
335 // With a delta base chosen any new delta must be "better".
336 // Retain the distribution described above.
337 d := int64(targetDepth)
338 n := targetSize
339
340 // If target depth is bigger than maxDepth, this delta is not suitable to be used.
341 if d >= maxDepth {
342 return 0
343 }
344
345 // If src is whole (depth=0) and base is near limit (depth=9/10)
346 // any delta using src can be 10x larger and still be better.
347 //
348 // If src is near limit (depth=9/10) and base is whole (depth=0)
349 // a new delta dependent on src must be 1/10th the size.
350 return n * (maxDepth - int64(baseDepth)) / (maxDepth - d)
351 }
352
353 type byTypeAndSize []*ObjectToPack
354
355 func (a byTypeAndSize) Len() int { return len(a) }
356
357 func (a byTypeAndSize) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
358
359 func (a byTypeAndSize) Less(i, j int) bool {
360 if a[i].Type() < a[j].Type() {
361 return false
362 }
363
364 if a[i].Type() > a[j].Type() {
365 return true
366 }
367
368 return a[i].Size() > a[j].Size()
369 }