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