]> git.openstreetmap.org Git - rails.git/blob - app/models/changeset.rb
Merge pull request #6394 from openstreetmap/dependabot/github_actions/ruby/setup...
[rails.git] / app / models / changeset.rb
1 # frozen_string_literal: true
2
3 # == Schema Information
4 #
5 # Table name: changesets
6 #
7 #  id                     :bigint           not null, primary key
8 #  user_id                :bigint           not null
9 #  created_at             :datetime         not null
10 #  min_lat                :integer
11 #  max_lat                :integer
12 #  min_lon                :integer
13 #  max_lon                :integer
14 #  closed_at              :datetime         not null
15 #  num_changes            :integer          default(0), not null
16 #  num_created_nodes      :integer          default(0), not null
17 #  num_modified_nodes     :integer          default(0), not null
18 #  num_deleted_nodes      :integer          default(0), not null
19 #  num_created_ways       :integer          default(0), not null
20 #  num_modified_ways      :integer          default(0), not null
21 #  num_deleted_ways       :integer          default(0), not null
22 #  num_created_relations  :integer          default(0), not null
23 #  num_modified_relations :integer          default(0), not null
24 #  num_deleted_relations  :integer          default(0), not null
25 #
26 # Indexes
27 #
28 #  changesets_bbox_idx                        (min_lat,max_lat,min_lon,max_lon) USING gist
29 #  changesets_closed_at_idx                   (closed_at)
30 #  changesets_created_at_idx                  (created_at)
31 #  changesets_user_id_created_at_idx          (user_id,created_at)
32 #  changesets_user_id_id_idx                  (user_id,id)
33 #  index_changesets_on_user_id_and_closed_at  (user_id,closed_at)
34 #
35 # Foreign Keys
36 #
37 #  changesets_user_id_fkey  (user_id => users.id)
38 #
39
40 class Changeset < ApplicationRecord
41   require "xml/libxml"
42
43   belongs_to :user, :counter_cache => true
44
45   has_many :changeset_tags
46
47   has_many :nodes
48   has_many :ways
49   has_many :relations
50   has_many :old_nodes
51   has_many :old_ways
52   has_many :old_relations
53
54   has_many :comments, -> { where(:visible => true).order(:created_at) }, :class_name => "ChangesetComment"
55   has_many :subscriptions, :class_name => "ChangesetSubscription"
56   has_many :subscribers, :through => :subscriptions
57
58   validates :id, :uniqueness => true, :presence => { :on => :update },
59                  :numericality => { :on => :update, :only_integer => true }
60   [:num_changes,
61    :num_created_nodes, :num_modified_nodes, :num_deleted_nodes,
62    :num_created_ways, :num_modified_ways, :num_deleted_ways,
63    :num_created_relations, :num_modified_relations, :num_deleted_relations].each do |counter_attribute|
64     validates counter_attribute, :presence => true,
65                                  :numericality => { :only_integer => true,
66                                                     :greater_than_or_equal_to => 0 }
67   end
68   validates :created_at, :closed_at, :presence => true
69   validates :min_lat, :max_lat, :min_lon, :max_lat, :allow_nil => true,
70                                                     :numericality => { :only_integer => true }
71
72   before_save :update_closed_at
73
74   # maximum number of elements allowed in a changeset
75   MAX_ELEMENTS = 10000
76
77   # maximum time a changeset is allowed to be open for.
78   MAX_TIME_OPEN = 1.day
79
80   # idle timeout increment, one hour seems reasonable.
81   IDLE_TIMEOUT = 1.hour
82
83   # Use a method like this, so that we can easily change how we
84   # determine whether a changeset is open, without breaking code in at
85   # least 6 controllers
86   def open?
87     # a changeset is open (that is, it will accept further changes) when
88     # it has not yet run out of time and its capacity is small enough.
89     # note that this may not be a hard limit - due to timing changes and
90     # concurrency it is possible that some changesets may be slightly
91     # longer than strictly allowed or have slightly more changes in them.
92     (closed_at > Time.now.utc) && (num_changes <= MAX_ELEMENTS)
93   end
94
95   def set_closed_time_now
96     self.closed_at = Time.now.utc if open?
97   end
98
99   def self.from_xml(xml, create: false)
100     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
101     doc = p.parse
102     pt = doc.find_first("//osm/changeset")
103
104     if pt
105       Changeset.from_xml_node(pt, :create => create)
106     else
107       raise OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
108     end
109   rescue LibXML::XML::Error, ArgumentError => e
110     raise OSM::APIBadXMLError.new("changeset", xml, e.message)
111   end
112
113   def self.from_xml_node(pt, create: false)
114     cs = Changeset.new
115     if create
116       cs.created_at = Time.now.utc
117       # initial close time is 1h ahead, but will be increased on each
118       # modification.
119       cs.closed_at = cs.created_at + IDLE_TIMEOUT
120       # initially we have no changes in a changeset
121       cs.num_changes = 0
122     end
123
124     pt.find("tag").each do |tag|
125       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing key") if tag["k"].nil?
126       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing value") if tag["v"].nil?
127
128       cs.add_tag_keyval(tag["k"], tag["v"])
129     end
130
131     cs
132   end
133
134   ##
135   # returns the bounding box of the changeset. it is possible that some
136   # or all of the values will be nil, indicating that they are undefined.
137   def bbox
138     @bbox ||= BoundingBox.new(min_lon, min_lat, max_lon, max_lat)
139   end
140
141   def bbox_valid?
142     bbox.complete?
143   end
144
145   ##
146   # expand the bounding box to include the given bounding box.
147   def update_bbox!(bbox_update)
148     bbox.expand!(bbox_update)
149
150     raise OSM::APISizeLimitExceeded if bbox.linear_size > size_limit
151
152     # update active record. rails 2.1's dirty handling should take care of
153     # whether this object needs saving or not.
154     self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox.to_a.collect(&:round) if bbox.complete?
155   end
156
157   ##
158   # the number of elements is also passed in so that we can ensure that
159   # a single changeset doesn't contain too many elements.
160   def add_changes!(elements)
161     self.num_changes += elements
162   end
163
164   def tags
165     unless @tags
166       @tags = {}
167       changeset_tags.each do |tag|
168         @tags[tag.k] = tag.v
169       end
170     end
171     @tags
172   end
173
174   attr_writer :tags
175
176   def add_tag_keyval(k, v)
177     @tags ||= {}
178
179     # duplicate tags are now forbidden, so we can't allow values
180     # in the hash to be overwritten.
181     raise OSM::APIDuplicateTagsError.new("changeset", id, k) if @tags.include? k
182
183     @tags[k] = v
184   end
185
186   def save_with_tags!
187     # do the changeset update and the changeset tags update in the
188     # same transaction to ensure consistency.
189     Changeset.transaction do
190       save!
191
192       tags = self.tags
193       ChangesetTag.where(:changeset => id).delete_all
194
195       tags.each do |k, v|
196         tag = ChangesetTag.new
197         tag.changeset_id = id
198         tag.k = k
199         tag.v = v
200         tag.save!
201       end
202     end
203   end
204
205   ##
206   # set the auto-close time to be one hour in the future unless
207   # that would make it more than 24h long, in which case clip to
208   # 24h, as this has been decided is a reasonable time limit.
209   def update_closed_at
210     if open?
211       self.closed_at = if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
212                          created_at + MAX_TIME_OPEN
213                        else
214                          Time.now.utc + IDLE_TIMEOUT
215                        end
216     end
217   end
218
219   ##
220   # update this instance from another instance given and the user who is
221   # doing the updating. note that this method is not for updating the
222   # bounding box, only the tags of the changeset.
223   def update_from(other, user)
224     # ensure that only the user who opened the changeset may modify it.
225     raise OSM::APIUserChangesetMismatchError unless user.id == user_id
226
227     # can't change a closed changeset
228     raise OSM::APIChangesetAlreadyClosedError, self unless open?
229
230     # copy the other's tags
231     self.tags = other.tags
232
233     save_with_tags!
234   end
235
236   def size_limit
237     @size_limit ||= ActiveRecord::Base.connection.select_value(
238       "SELECT api_size_limit($1)", "api_size_limit", [user_id]
239     )
240   end
241
242   def num_created_elements = num_created_nodes + num_created_ways + num_created_relations
243   def num_modified_elements = num_modified_nodes + num_modified_ways + num_modified_relations
244   def num_deleted_elements = num_deleted_nodes + num_deleted_ways + num_deleted_relations
245
246   def num_changed_nodes = num_created_nodes + num_modified_nodes + num_deleted_nodes
247   def num_changed_ways = num_created_ways + num_modified_ways + num_deleted_ways
248   def num_changed_relations = num_created_relations + num_modified_relations + num_deleted_relations
249
250   def num_type_changes_in_sync?
251     num_changes == num_created_elements + num_modified_elements + num_deleted_elements
252   end
253
254   def actual_num_changed_nodes = num_type_changes_in_sync? ? num_changed_nodes : old_nodes.count
255   def actual_num_changed_ways = num_type_changes_in_sync? ? num_changed_ways : old_ways.count
256   def actual_num_changed_relations = num_type_changes_in_sync? ? num_changed_relations : old_relations.count
257 end