]> git.openstreetmap.org Git - rails.git/blob - lib/diff_reader.rb
Merge remote-tracking branch 'upstream/pull/2921' into master
[rails.git] / lib / diff_reader.rb
1 ##
2 # DiffReader reads OSM diffs and applies them to the database.
3 #
4 # Uses the streaming LibXML "Reader" interface to cut down on memory
5 # usage, so hopefully we can process fairly large diffs.
6 class DiffReader
7   include ConsistencyValidations
8
9   # maps each element type to the model class which handles it
10   MODELS = {
11     "node" => Node,
12     "way" => Way,
13     "relation" => Relation
14   }.freeze
15
16   ##
17   # Construct a diff reader by giving it a bunch of XML +data+ to parse
18   # in OsmChange format. All diffs must be limited to a single changeset
19   # given in +changeset+.
20   def initialize(data, changeset)
21     @reader = XML::Reader.string(data)
22     @changeset = changeset
23     # document that's (re-)used to handle elements expanded out of the
24     # diff processing stream.
25     @doc = XML::Document.new
26     @doc.root = XML::Node.new("osm")
27   end
28
29   ##
30   # Reads the next element from the XML document. Checks the return value
31   # and throws an exception if an error occurred.
32   def read_or_die
33     # NOTE: XML::Reader#read returns false for EOF and raises an
34     # exception if an error occurs.
35     @reader.read
36   rescue LibXML::XML::Error => e
37     raise OSM::APIBadXMLError.new("changeset", xml, e.message)
38   end
39
40   ##
41   # An element-block mapping for using the LibXML reader interface.
42   #
43   # Since a lot of LibXML reader usage is boilerplate iteration through
44   # elements, it would be better to DRY and do this in a block. This
45   # could also help with error handling...?
46   def with_element
47     # if the start element is empty then don't do any processing, as
48     # there won't be any child elements to process!
49     unless @reader.empty_element?
50       # read the first element
51       read_or_die
52
53       while @reader.node_type != 15 # end element
54         # because we read elements in DOM-style to reuse their DOM
55         # parsing code, we don't always read an element on each pass
56         # as the call to @reader.next in the innermost loop will take
57         # care of that for us.
58         if @reader.node_type == 1 # element
59           name = @reader.name
60           attributes = {}
61
62           if @reader.has_attributes?
63             attributes[@reader.name] = @reader.value while @reader.move_to_next_attribute == 1
64
65             @reader.move_to_element
66           end
67
68           yield name, attributes
69         else
70           read_or_die
71         end
72       end
73     end
74     read_or_die
75   end
76
77   ##
78   # An element-block mapping for using the LibXML reader interface.
79   #
80   # Since a lot of LibXML reader usage is boilerplate iteration through
81   # elements, it would be better to DRY and do this in a block. This
82   # could also help with error handling...?
83   def with_model
84     with_element do |model_name, _model_attributes|
85       model = MODELS[model_name]
86       if model.nil?
87         raise OSM::APIBadUserInput, "Unexpected element type #{model_name}, " \
88                                        "expected node, way or relation."
89       end
90       # new in libxml-ruby >= 2, expand returns an element not associated
91       # with a document. this means that there's no encoding parameter,
92       # which means basically nothing works.
93       expanded = @reader.expand
94
95       # create a new, empty document to hold this expanded node
96       new_node = @doc.import(expanded)
97       @doc.root << new_node
98
99       yield model, new_node
100       @reader.next
101
102       # remove element from doc - it will be garbage collected and the
103       # rest of the document is re-used in the next iteration.
104       @doc.root.child.remove!
105     end
106   end
107
108   ##
109   # Checks a few invariants. Others are checked in the model methods
110   # such as save_ and delete_with_history.
111   def check(model, xml, new)
112     raise OSM::APIBadXMLError.new(model, xml) if new.nil?
113     raise OSM::APIChangesetMismatchError.new(new.changeset_id, @changeset.id) unless new.changeset_id == @changeset.id
114   end
115
116   ##
117   # Consume the XML diff and try to commit it to the database. This code
118   # is *not* transactional, so code which calls it should ensure that the
119   # appropriate transaction block is in place.
120   #
121   # On a failure to meet preconditions (e.g: optimistic locking fails)
122   # an exception subclassing OSM::APIError will be thrown.
123   def commit
124     # data structure used for mapping placeholder IDs to real IDs
125     ids = { :node => {}, :way => {}, :relation => {} }
126
127     # take the first element and check that it is an osmChange element
128     @reader.read
129     raise OSM::APIBadUserInput, "Document element should be 'osmChange'." if @reader.name != "osmChange"
130
131     result = OSM::API.new.get_xml_doc
132     result.root.name = "diffResult"
133
134     # loop at the top level, within the <osmChange> element
135     with_element do |action_name, action_attributes|
136       case action_name
137       when "create"
138         # create a new element. this code is agnostic of the element type
139         # because all the elements support the methods that we're using.
140         with_model do |model, xml|
141           new = model.from_xml_node(xml, :create => true)
142           check(model, xml, new)
143
144           # when this element is saved it will get a new ID, so we save it
145           # to produce the mapping which is sent to other elements.
146           placeholder_id = xml["id"].to_i
147           raise OSM::APIBadXMLError.new(model, xml) if placeholder_id.nil?
148
149           # check if the placeholder ID has been given before and throw
150           # an exception if it has - we can't create the same element twice.
151           model_sym = model.to_s.downcase.to_sym
152           raise OSM::APIBadUserInput, "Placeholder IDs must be unique for created elements." if ids[model_sym].include? placeholder_id
153
154           # some elements may have placeholders for other elements in the
155           # diff, so we must fix these before saving the element.
156           new.fix_placeholders!(ids, placeholder_id)
157
158           # create element given user
159           new.create_with_history(@changeset.user)
160
161           # save placeholder => allocated ID map
162           ids[model_sym][placeholder_id] = new.id
163
164           # add the result to the document we're building for return.
165           xml_result = XML::Node.new model.to_s.downcase
166           xml_result["old_id"] = placeholder_id.to_s
167           xml_result["new_id"] = new.id.to_s
168           xml_result["new_version"] = new.version.to_s
169           result.root << xml_result
170         end
171
172       when "modify"
173         # modify an existing element. again, this code doesn't directly deal
174         # with types, but uses duck typing to handle them transparently.
175         with_model do |model, xml|
176           # get the new element from the XML payload
177           new = model.from_xml_node(xml, :create => false)
178           check(model, xml, new)
179
180           # if the ID is a placeholder then map it to the real ID
181           model_sym = model.to_s.downcase.to_sym
182           client_id = new.id
183           is_placeholder = ids[model_sym].include? client_id
184           id = is_placeholder ? ids[model_sym][client_id] : client_id
185
186           # and the old one from the database
187           old = model.find(id)
188
189           # translate any placeholder IDs to their true IDs.
190           new.fix_placeholders!(ids)
191           new.id = id
192
193           old.update_from(new, @changeset.user)
194
195           xml_result = XML::Node.new model.to_s.downcase
196           xml_result["old_id"] = client_id.to_s
197           xml_result["new_id"] = id.to_s
198           # version is updated in "old" through the update, so we must not
199           # return new.version here but old.version!
200           xml_result["new_version"] = old.version.to_s
201           result.root << xml_result
202         end
203
204       when "delete"
205         # delete action. this takes a payload in API 0.6, so we need to do
206         # most of the same checks that are done for the modify.
207         with_model do |model, xml|
208           # delete doesn't have to contain a full payload, according to
209           # the wiki docs, so we just extract the things we need.
210           new_id = xml["id"].to_i
211           raise OSM::APIBadXMLError.new(model, xml, "ID attribute is required") if new_id.nil?
212
213           # if the ID is a placeholder then map it to the real ID
214           model_sym = model.to_s.downcase.to_sym
215           is_placeholder = ids[model_sym].include? new_id
216           id = is_placeholder ? ids[model_sym][new_id] : new_id
217
218           # build the "new" element by modifying the existing one
219           new = model.find(id)
220           new.changeset_id = xml["changeset"].to_i
221           new.version = xml["version"].to_i
222           check(model, xml, new)
223
224           # fetch the matching old element from the DB
225           old = model.find(id)
226
227           # can a delete have placeholders under any circumstances?
228           # if a way is modified, then deleted is that a valid diff?
229           new.fix_placeholders!(ids)
230
231           xml_result = XML::Node.new model.to_s.downcase
232           # oh, the irony... the "new" element actually contains the "old" ID
233           # a better name would have been client/server, but anyway...
234           xml_result["old_id"] = new_id.to_s
235
236           if action_attributes["if-unused"]
237             begin
238               old.delete_with_history!(new, @changeset.user)
239             rescue OSM::APIAlreadyDeletedError, OSM::APIPreconditionFailedError
240               xml_result["new_id"] = old.id.to_s
241               xml_result["new_version"] = old.version.to_s
242             end
243           else
244             old.delete_with_history!(new, @changeset.user)
245           end
246
247           result.root << xml_result
248         end
249
250       else
251         # no other actions to choose from, so it must be the users fault!
252         raise OSM::APIChangesetActionInvalid, action_name
253       end
254     end
255
256     # return the XML document to be rendered back to the client
257     result
258   end
259 end