]> git.openstreetmap.org Git - rails.git/blob - lib/diff_reader.rb
Log the request on a few requests when there is a bad request, probably should do...
[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   # An element-block mapping for using the LibXML reader interface. 
27   #
28   # Since a lot of LibXML reader usage is boilerplate iteration through
29   # elements, it would be better to DRY and do this in a block. This
30   # could also help with error handling...?
31   def with_element
32     # skip the first element, which is our opening element of the block
33     @reader.read
34     # loop over all elements. 
35     # NOTE: XML::Reader#read returns 0 for EOF and -1 for error.
36     while @reader.read == 1
37       break if @reader.node_type == 15 # end element
38       next unless @reader.node_type == 1 # element
39       yield @reader.name
40     end
41   end
42
43   ##
44   # An element-block mapping for using the LibXML reader interface. 
45   #
46   # Since a lot of LibXML reader usage is boilerplate iteration through
47   # elements, it would be better to DRY and do this in a block. This
48   # could also help with error handling...?
49   def with_model
50     with_element do |model_name|
51       model = MODELS[model_name]
52       raise "Unexpected element type #{model_name}, " +
53         "expected node, way, relation." if model.nil?
54       yield model, @reader.expand
55       @reader.next
56     end
57   end
58
59   ##
60   # Checks a few invariants. Others are checked in the model methods
61   # such as save_ and delete_with_history.
62   def check(model, xml, new)
63     raise OSM::APIBadXMLError.new(model, xml) if new.nil?
64     unless new.changeset_id == @changeset.id 
65       raise OSM::APIChangesetMismatchError.new(new.changeset_id, @changeset.id)
66     end
67   end
68
69   ##
70   # Consume the XML diff and try to commit it to the database. This code
71   # is *not* transactional, so code which calls it should ensure that the
72   # appropriate transaction block is in place.
73   #
74   # On a failure to meet preconditions (e.g: optimistic locking fails) 
75   # an exception subclassing OSM::APIError will be thrown.
76   def commit
77
78     node_ids, way_ids, rel_ids = {}, {}, {}
79     ids = { :node => node_ids, :way => way_ids, :relation => rel_ids}
80
81     result = OSM::API.new.get_xml_doc
82     result.root.name = "diffResult"
83
84     # loop at the top level, within the <osmChange> element (although we
85     # don't actually check this...)
86     with_element do |action_name|
87       if action_name == 'create'
88         # create a new element. this code is agnostic of the element type
89         # because all the elements support the methods that we're using.
90         with_model do |model, xml|
91           new = model.from_xml_node(xml, true)
92           check(model, xml, new)
93
94           # when this element is saved it will get a new ID, so we save it
95           # to produce the mapping which is sent to other elements.
96           placeholder_id = xml['id'].to_i
97           raise OSM::APIBadXMLError.new(model, xml) if placeholder_id.nil?
98
99           # some elements may have placeholders for other elements in the
100           # diff, so we must fix these before saving the element.
101           new.fix_placeholders!(ids)
102
103           # create element given user
104           new.create_with_history(@changeset.user)
105           
106           # save placeholder => allocated ID map
107           ids[model.to_s.downcase.to_sym][placeholder_id] = new.id
108
109           # add the result to the document we're building for return.
110           xml_result = XML::Node.new model.to_s.downcase
111           xml_result["old_id"] = placeholder_id.to_s
112           xml_result["new_id"] = new.id.to_s
113           xml_result["new_version"] = new.version.to_s
114           result.root << xml_result
115         end
116         
117       elsif action_name == 'modify'
118         # modify an existing element. again, this code doesn't directly deal
119         # with types, but uses duck typing to handle them transparently.
120         with_model do |model, xml|
121           # get the new element from the XML payload
122           new = model.from_xml_node(xml, false)
123           check(model, xml, new)
124
125           # and the old one from the database
126           old = model.find(new.id)
127
128           new.fix_placeholders!(ids)
129           old.update_from(new, @changeset.user)
130
131           xml_result = XML::Node.new model.to_s.downcase
132           xml_result["old_id"] = old.id.to_s
133           xml_result["new_id"] = new.id.to_s 
134           # version is updated in "old" through the update, so we must not
135           # return new.version here but old.version!
136           xml_result["new_version"] = old.version.to_s
137           result.root << xml_result
138         end
139
140       elsif action_name == 'delete'
141         # delete action. this takes a payload in API 0.6, so we need to do
142         # most of the same checks that are done for the modify.
143         with_model do |model, xml|
144           new = model.from_xml_node(xml, false)
145           check(model, xml, new)
146
147           old = model.find(new.id)
148
149           # can a delete have placeholders under any circumstances?
150           # if a way is modified, then deleted is that a valid diff?
151           new.fix_placeholders!(ids)
152           old.delete_with_history!(new, @changeset.user)
153
154           xml_result = XML::Node.new model.to_s.downcase
155           xml_result["old_id"] = old.id.to_s
156           result.root << xml_result
157         end
158
159       else
160         # no other actions to choose from, so it must be the users fault!
161         raise OSM::APIChangesetActionInvalid.new(action_name)
162       end
163     end
164
165     # return the XML document to be rendered back to the client
166     return result
167   end
168
169 end