]> git.openstreetmap.org Git - rails.git/blob - lib/diff_reader.rb
fix backspacing through way to delete it
[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   }
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.new data
22     @changeset = changeset
23   end
24
25   ##
26   # Reads the next element from the XML document. Checks the return value
27   # and throws an exception if an error occurred.
28   def read_or_die
29     # NOTE: XML::Reader#read returns 0 for EOF and -1 for error.
30     # we allow an EOF because we are expecting this to always happen
31     # at the end of a document.
32     if @reader.read < 0
33       raise APIBadUserInput.new("Unexpected end of XML document.")
34     end
35   end
36
37   ##
38   # An element-block mapping for using the LibXML reader interface. 
39   #
40   # Since a lot of LibXML reader usage is boilerplate iteration through
41   # elements, it would be better to DRY and do this in a block. This
42   # could also help with error handling...?
43   def with_element
44     # if the start element is empty then don't do any processing, as
45     # there won't be any child elements to process!
46     unless @reader.empty_element?
47       # read the first element
48       read_or_die
49
50       while @reader.node_type != 15 do # end element
51         # because we read elements in DOM-style to reuse their DOM
52         # parsing code, we don't always read an element on each pass
53         # as the call to @reader.next in the innermost loop will take
54         # care of that for us.
55         if @reader.node_type == 1 # element
56           yield @reader.name
57         else
58           read_or_die
59         end
60       end 
61     end
62     read_or_die
63   end
64
65   ##
66   # An element-block mapping for using the LibXML reader interface. 
67   #
68   # Since a lot of LibXML reader usage is boilerplate iteration through
69   # elements, it would be better to DRY and do this in a block. This
70   # could also help with error handling...?
71   def with_model
72     with_element do |model_name|
73       model = MODELS[model_name]
74       raise "Unexpected element type #{model_name}, " +
75         "expected node, way, relation." if model.nil?
76       yield model, @reader.expand
77       @reader.next
78     end
79   end
80
81   ##
82   # Checks a few invariants. Others are checked in the model methods
83   # such as save_ and delete_with_history.
84   def check(model, xml, new)
85     raise OSM::APIBadXMLError.new(model, xml) if new.nil?
86     unless new.changeset_id == @changeset.id 
87       raise OSM::APIChangesetMismatchError.new(new.changeset_id, @changeset.id)
88     end
89   end
90
91   ##
92   # Consume the XML diff and try to commit it to the database. This code
93   # is *not* transactional, so code which calls it should ensure that the
94   # appropriate transaction block is in place.
95   #
96   # On a failure to meet preconditions (e.g: optimistic locking fails) 
97   # an exception subclassing OSM::APIError will be thrown.
98   def commit
99
100     # data structure used for mapping placeholder IDs to real IDs
101     node_ids, way_ids, rel_ids = {}, {}, {}
102     ids = { :node => node_ids, :way => way_ids, :relation => rel_ids}
103
104     # take the first element and check that it is an osmChange element
105     @reader.read
106     raise APIBadUserInput.new("Document element should be 'osmChange'.") if @reader.name != 'osmChange'
107
108     result = OSM::API.new.get_xml_doc
109     result.root.name = "diffResult"
110
111     # loop at the top level, within the <osmChange> element
112     with_element do |action_name|
113       if action_name == 'create'
114         # create a new element. this code is agnostic of the element type
115         # because all the elements support the methods that we're using.
116         with_model do |model, xml|
117           new = model.from_xml_node(xml, true)
118           check(model, xml, new)
119
120           # when this element is saved it will get a new ID, so we save it
121           # to produce the mapping which is sent to other elements.
122           placeholder_id = xml['id'].to_i
123           raise OSM::APIBadXMLError.new(model, xml) if placeholder_id.nil?
124
125           # check if the placeholder ID has been given before and throw
126           # an exception if it has - we can't create the same element twice.
127           model_sym = model.to_s.downcase.to_sym
128           raise OSM::APIBadUserInput.new("Placeholder IDs must be unique for created elements.") if ids[model_sym].include? placeholder_id
129
130           # some elements may have placeholders for other elements in the
131           # diff, so we must fix these before saving the element.
132           new.fix_placeholders!(ids)
133
134           # create element given user
135           new.create_with_history(@changeset.user)
136           
137           # save placeholder => allocated ID map
138           ids[model_sym][placeholder_id] = new.id
139
140           # add the result to the document we're building for return.
141           xml_result = XML::Node.new model.to_s.downcase
142           xml_result["old_id"] = placeholder_id.to_s
143           xml_result["new_id"] = new.id.to_s
144           xml_result["new_version"] = new.version.to_s
145           result.root << xml_result
146         end
147         
148       elsif action_name == 'modify'
149         # modify an existing element. again, this code doesn't directly deal
150         # with types, but uses duck typing to handle them transparently.
151         with_model do |model, xml|
152           # get the new element from the XML payload
153           new = model.from_xml_node(xml, false)
154           check(model, xml, new)
155
156           # if the ID is a placeholder then map it to the real ID
157           model_sym = model.to_s.downcase.to_sym
158           is_placeholder = ids[model_sym].include? new.id
159           id = is_placeholder ? ids[model_sym][new.id] : new.id
160
161           # and the old one from the database
162           old = model.find(id)
163
164           new.fix_placeholders!(ids)
165           old.update_from(new, @changeset.user)
166
167           xml_result = XML::Node.new model.to_s.downcase
168           # oh, the irony... the "new" element actually contains the "old" ID
169           # a better name would have been client/server, but anyway...
170           xml_result["old_id"] = new.id.to_s
171           xml_result["new_id"] = id.to_s 
172           # version is updated in "old" through the update, so we must not
173           # return new.version here but old.version!
174           xml_result["new_version"] = old.version.to_s
175           result.root << xml_result
176         end
177
178       elsif action_name == 'delete'
179         # delete action. this takes a payload in API 0.6, so we need to do
180         # most of the same checks that are done for the modify.
181         with_model do |model, xml|
182           # delete doesn't have to contain a full payload, according to
183           # the wiki docs, so we just extract the things we need.
184           new_id = xml['id'].to_i
185           raise API::APIBadXMLError.new(model, xml, "ID attribute is required") if new_id.nil?
186
187           # if the ID is a placeholder then map it to the real ID
188           model_sym = model.to_s.downcase.to_sym
189           is_placeholder = ids[model_sym].include? new_id
190           id = is_placeholder ? ids[model_sym][new_id] : new_id
191
192           # build the "new" element by modifying the existing one
193           new = model.find(id)
194           new.changeset_id = xml['changeset'].to_i
195           new.version = xml['version'].to_i
196           check(model, xml, new)
197
198           # fetch the matching old element from the DB
199           old = model.find(id)
200
201           # can a delete have placeholders under any circumstances?
202           # if a way is modified, then deleted is that a valid diff?
203           new.fix_placeholders!(ids)
204           old.delete_with_history!(new, @changeset.user)
205
206           xml_result = XML::Node.new model.to_s.downcase
207           # oh, the irony... the "new" element actually contains the "old" ID
208           # a better name would have been client/server, but anyway...
209           xml_result["old_id"] = new_id.to_s
210           result.root << xml_result
211         end
212
213       else
214         # no other actions to choose from, so it must be the users fault!
215         raise OSM::APIChangesetActionInvalid.new(action_name)
216       end
217     end
218
219     # return the XML document to be rendered back to the client
220     return result
221   end
222
223 end