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