]> git.openstreetmap.org Git - rails.git/blob - lib/diff_reader.rb
d793f63e7bfda199d1ecc73b8d7dd6e32c8aa69d
[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
83     # loop at the top level, within the <osmChange> element (although we
84     # don't actually check this...)
85     with_element do |action_name|
86       if action_name == 'create'
87         # create a new element. this code is agnostic of the element type
88         # because all the elements support the methods that we're using.
89         with_model do |model, xml|
90           new = model.from_xml_node(xml, true)
91           check(model, xml, new)
92
93           # when this element is saved it will get a new ID, so we save it
94           # to produce the mapping which is sent to other elements.
95           placeholder_id = xml['id'].to_i
96           raise OSM::APIBadXMLError.new(model, xml) if placeholder_id.nil?
97
98           # some elements may have placeholders for other elements in the
99           # diff, so we must fix these before saving the element.
100           new.fix_placeholders!(ids)
101
102           # create element given user
103           new.create_with_history(@changeset.user)
104           
105           # save placeholder => allocated ID map
106           ids[model.to_s.downcase.to_sym][placeholder_id] = new.id
107
108           # add the result to the document we're building for return.
109           xml_result = XML::Node.new model.to_s.downcase
110           xml_result["old_id"] = placeholder_id.to_s
111           xml_result["new_id"] = new.id.to_s
112           xml_result["new_version"] = new.version.to_s
113           result.root << xml_result
114         end
115         
116       elsif action_name == 'modify'
117         # modify an existing element. again, this code doesn't directly deal
118         # with types, but uses duck typing to handle them transparently.
119         with_model do |model, xml|
120           # get the new element from the XML payload
121           new = model.from_xml_node(xml, false)
122           check(model, xml, new)
123
124           # and the old one from the database
125           old = model.find(new.id)
126
127           new.fix_placeholders!(ids)
128           old.update_from(new, @changeset.user)
129
130           xml_result = XML::Node.new model.to_s.downcase
131           xml_result["old_id"] = old.id.to_s
132           xml_result["new_id"] = new.id.to_s
133           xml_result["new_version"] = new.version.to_s
134           result.root << xml_result
135         end
136
137       elsif action_name == 'delete'
138         # delete action. this takes a payload in API 0.6, so we need to do
139         # most of the same checks that are done for the modify.
140         with_model do |model, xml|
141           new = model.from_xml_node(xml, false)
142           check(model, xml, new)
143
144           old = model.find(new.id)
145
146           # can a delete have placeholders under any circumstances?
147           # if a way is modified, then deleted is that a valid diff?
148           new.fix_placeholders!(ids)
149           old.delete_with_history!(new, @changeset.user)
150
151           xml_result = XML::Node.new model.to_s.downcase
152           xml_result["old_id"] = old.id.to_s
153           result.root << xml_result
154         end
155
156       else
157         # no other actions to choose from, so it must be the users fault!
158         raise OSM::APIChangesetActionInvalid.new(action_name)
159       end
160     end
161
162     # return the XML document to be rendered back to the client
163     return result
164   end
165
166 end