-
Notifications
You must be signed in to change notification settings - Fork 7
/
decoder.go
406 lines (327 loc) · 9.94 KB
/
decoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Copyright 2017-21 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pbf
import (
"bytes"
"compress/zlib"
"context"
"errors"
"fmt"
"io"
"reflect"
"runtime"
"time"
"google.golang.org/protobuf/proto"
"m4o.io/pbf/protobuf"
)
const (
// DefaultBufferSize is the default buffer size for protobuf un-marshaling
DefaultBufferSize = 1024 * 1024
// DefaultInputChannelLength is the default channel length of raw blobs
DefaultInputChannelLength = 16
// DefaultOutputChannelLength is the default channel length of decoded arrays of element
DefaultOutputChannelLength = 8
// DefaultDecodedChannelLength is the default channel length of decoded elements coalesced from output channels
DefaultDecodedChannelLength = 8000
)
// DefaultNCpu provides the default number of CPUs.
func DefaultNCpu() uint16 {
return uint16(runtime.GOMAXPROCS(-1))
}
type encoded struct {
header *protobuf.BlobHeader
blob *protobuf.Blob
err error
}
type decoded struct {
elements []interface{}
err error
}
type pair struct {
element interface{}
err error
}
// Decoder reads and decodes OpenStreetMap PBF data from an input stream.
type Decoder struct {
Header Header
pairs chan pair
cancel context.CancelFunc
}
// decoderOptions provides optional configuration parameters for Decoder construction.
type decoderOptions struct {
protoBufferSize int // buffer size for protobuf un-marshaling
inputChannelLength int // channel length of raw blobs
outputChannelLength int // channel length of decoded arrays of element
decodedChannelLength int // channel length of decoded elements coalesced from output channels
nCPU uint16 // the number of CPUs to use for background processing
}
// DecoderOption configures how we set up the decoder.
type DecoderOption func(*decoderOptions)
// WithProtoBufferSize lets you set the buffer size for protobuf un-marshaling.
func WithProtoBufferSize(s int) DecoderOption {
return func(o *decoderOptions) {
o.protoBufferSize = s
}
}
// WithInputChannelLength lets you set the channel length of raw blobs.
func WithInputChannelLength(l int) DecoderOption {
return func(o *decoderOptions) {
o.inputChannelLength = l
}
}
// WithOutputChannelLength lets you set the channel length of decoded arrays of element.
func WithOutputChannelLength(l int) DecoderOption {
return func(o *decoderOptions) {
o.outputChannelLength = l
}
}
// WithDecodedChannelLength lets you set the channel length of decoded elements coalesced from output channels.
func WithDecodedChannelLength(l int) DecoderOption {
return func(o *decoderOptions) {
o.decodedChannelLength = l
}
}
// WithNCpus lets you set the number of CPUs to use for background processing.
func WithNCpus(n uint16) DecoderOption {
return func(o *decoderOptions) {
o.nCPU = n
}
}
// defaultDecoderConfig provides a default configuration for decoders.
var defaultDecoderConfig = decoderOptions{
protoBufferSize: DefaultBufferSize,
inputChannelLength: DefaultInputChannelLength,
outputChannelLength: DefaultOutputChannelLength,
decodedChannelLength: DefaultDecodedChannelLength,
nCPU: DefaultNCpu(),
}
// NewDecoder returns a new decoder, configured with cfg, that reads from
// reader. The decoder is initialized with the OSM header.
func NewDecoder(ctx context.Context, reader io.Reader, opts ...DecoderOption) (*Decoder, error) {
d := &Decoder{}
c := defaultDecoderConfig
for _, opt := range opts {
opt(&c)
}
ctx, d.cancel = context.WithCancel(ctx)
r := newBlobReader(reader)
buf := bytes.NewBuffer(make([]byte, 0, c.protoBufferSize))
h, err := r.readBlobHeader(buf)
if err != nil {
return nil, err
}
b, err := r.readBlob(buf, h)
if err != nil {
return nil, err
}
e, err := elements(h, b, bytes.NewBuffer(make([]byte, 0, 1024)))
if err != nil {
return nil, err
}
if e[0].(*Header) == nil {
err = fmt.Errorf("expected header data but got %v", reflect.TypeOf(e[0]))
return nil, err
}
d.Header = *e[0].(*Header)
// create decoding pipelines
var outputs []chan decoded
for _, input := range read(ctx, r, c) {
outputs = append(outputs, decode(input, c))
}
d.pairs = coalesce(c, outputs...)
return d, nil
}
// Decode reads the next OSM object and returns either a pointer to Node, Way
// or Relation struct representing the underlying OpenStreetMap PBF data, or
// error encountered. The end of the input stream is reported by an io.EOF
// error.
func (d *Decoder) Decode() (interface{}, error) {
decoded, more := <-d.pairs
if !more {
return nil, io.EOF
}
return decoded.element, decoded.err
}
// Close will cancel the background decoding pipeline.
func (d *Decoder) Close() {
d.cancel()
}
// read obtains OSM blobs and sends them down, in a round-robin manner, a list
// of channels to be decoded.
func read(ctx context.Context, b blobReader, cfg decoderOptions) (inputs []chan encoded) {
n := cfg.nCPU
for i := uint16(0); i < n; i++ {
inputs = append(inputs, make(chan encoded, cfg.inputChannelLength))
}
go func() {
defer func() {
for _, input := range inputs {
close(input)
}
}()
buffer := bytes.NewBuffer(make([]byte, 0, cfg.protoBufferSize))
var i uint16
for {
input := inputs[i]
i = (i + 1) % n
h, err := b.readBlobHeader(buffer)
if err == io.EOF {
return
} else if err != nil {
input <- encoded{err: err}
return
}
b, err := b.readBlob(buffer, h)
if err != nil {
input <- encoded{err: err}
return
}
select {
case <-ctx.Done():
return
case input <- encoded{header: h, blob: b}:
}
}
}()
return inputs
}
// decode decodes blob/header pairs into an array of OSM elements. These
// arrays are placed onto an output channel where they will be coalesced into
// their correct order.
func decode(input <-chan encoded, cfg decoderOptions) (output chan decoded) {
output = make(chan decoded, cfg.outputChannelLength)
buf := bytes.NewBuffer(make([]byte, 0, cfg.protoBufferSize))
go func() {
defer close(output)
for {
raw, more := <-input
if !more {
return
}
if raw.err != nil {
output <- decoded{nil, raw.err}
return
}
elements, err := elements(raw.header, raw.blob, buf)
output <- decoded{elements, err}
}
}()
return
}
// coalesce merges the list of channels in a round-robin manner and sends the
// elements in pairs down a channel of pairs.
func coalesce(cfg decoderOptions, outputs ...chan decoded) (pairs chan pair) {
pairs = make(chan pair, cfg.decodedChannelLength)
go func() {
defer close(pairs)
n := len(outputs)
var i int
for {
output := outputs[i]
i = (i + 1) % n
decoded, more := <-output
if !more {
// Since the channels are inspected round-robin, when one channel
// is done, all subsequent channels are done.
return
}
if decoded.err != nil {
pairs <- pair{nil, decoded.err}
return
}
for _, e := range decoded.elements {
pairs <- pair{e, nil}
}
}
}()
return pairs
}
// elements unmarshals an array of OSM elements from an array of protobuf encoded
// bytes. The bytes could possibly be compressed; zlibBuf is used to facilitate
// decompression.
func elements(header *protobuf.BlobHeader, blob *protobuf.Blob, zlibBuf *bytes.Buffer) ([]interface{}, error) {
var buf []byte
switch {
case blob.Raw != nil:
buf = blob.GetRaw()
case blob.ZlibData != nil:
r, err := zlib.NewReader(bytes.NewReader(blob.GetZlibData()))
if err != nil {
return nil, err
}
zlibBuf.Reset()
rawBufferSize := int(blob.GetRawSize() + bytes.MinRead)
if rawBufferSize > zlibBuf.Cap() {
zlibBuf.Grow(rawBufferSize)
}
_, err = zlibBuf.ReadFrom(r)
if err != nil {
return nil, err
}
if zlibBuf.Len() != int(blob.GetRawSize()) {
err = fmt.Errorf("raw blob data size %d but expected %d", zlibBuf.Len(), blob.GetRawSize())
return nil, err
}
buf = zlibBuf.Bytes()
default:
return nil, errors.New("unknown blob data type")
}
ht := *header.Type
switch ht {
case "OSMHeader":
{
h, err := parseOSMHeader(buf)
if err != nil {
return nil, err
}
return []interface{}{h}, nil
}
case "OSMData":
return parsePrimitiveBlock(buf)
default:
return nil, fmt.Errorf("unknown header type %s", ht)
}
}
// parseOSMHeader unmarshals the OSM header from an array of protobuf encoded bytes.
func parseOSMHeader(buffer []byte) (*Header, error) {
hb := &protobuf.HeaderBlock{}
if err := proto.Unmarshal(buffer, hb); err != nil {
return nil, err
}
header := &Header{
RequiredFeatures: hb.GetRequiredFeatures(),
OptionalFeatures: hb.GetOptionalFeatures(),
WritingProgram: hb.GetWritingprogram(),
Source: hb.GetSource(),
OsmosisReplicationBaseURL: hb.GetOsmosisReplicationBaseUrl(),
OsmosisReplicationSequenceNumber: hb.GetOsmosisReplicationSequenceNumber(),
}
if hb.Bbox != nil {
header.BoundingBox = BoundingBox{
Left: toDegrees(0, 1, hb.Bbox.GetLeft()),
Right: toDegrees(0, 1, hb.Bbox.GetRight()),
Top: toDegrees(0, 1, hb.Bbox.GetTop()),
Bottom: toDegrees(0, 1, hb.Bbox.GetBottom()),
}
}
if hb.OsmosisReplicationTimestamp != nil {
header.OsmosisReplicationTimestamp = time.Unix(*hb.OsmosisReplicationTimestamp, 0)
}
return header, nil
}
// toDegrees converts a coordinate into Degrees, given the offset and
// granularity of the coordinate.
func toDegrees(offset int64, granularity int32, coordinate int64) Degrees {
return 1e-9 * Degrees(offset+(int64(granularity)*coordinate))
}