From 4ec1771165ab8dd40e52804fd087eacfab25290b Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Thu, 28 Sep 2017 15:31:31 +0200 Subject: Add ability to specify alternative text for media attachments (#5123) * Fix #117 - Add ability to specify alternative text for media attachments - POST /api/v1/media accepts `description` straight away - PUT /api/v1/media/:id to update `description` (only for unattached ones) - Serialized as `name` of Document object in ActivityPub - Uploads form adjusted for better performance and description input * Add tests * Change undo button blend mode to difference --- db/migrate/20170927215609_add_description_to_media_attachments.rb | 5 +++++ db/schema.rb | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20170927215609_add_description_to_media_attachments.rb (limited to 'db') diff --git a/db/migrate/20170927215609_add_description_to_media_attachments.rb b/db/migrate/20170927215609_add_description_to_media_attachments.rb new file mode 100644 index 000000000..db8d76566 --- /dev/null +++ b/db/migrate/20170927215609_add_description_to_media_attachments.rb @@ -0,0 +1,5 @@ +class AddDescriptionToMediaAttachments < ActiveRecord::Migration[5.1] + def change + add_column :media_attachments, :description, :text + end +end diff --git a/db/schema.rb b/db/schema.rb index e16599d32..90f8a5683 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20170924022025) do +ActiveRecord::Schema.define(version: 20170927215609) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -161,6 +161,7 @@ ActiveRecord::Schema.define(version: 20170924022025) do t.string "shortcode" t.integer "type", default: 0, null: false t.json "file_meta" + t.text "description" t.index ["account_id"], name: "index_media_attachments_on_account_id" t.index ["shortcode"], name: "index_media_attachments_on_shortcode", unique: true t.index ["status_id"], name: "index_media_attachments_on_status_id" -- cgit From 97c02c3389b31b2459ffa157c91b7515ee1f626b Mon Sep 17 00:00:00 2001 From: aschmitz Date: Mon, 2 Oct 2017 14:28:59 -0500 Subject: Make IdsToBigints (mostly!) non-blocking (#5088) * Make IdsToBigints (mostly!) non-blocking This pulls in GitLab's MigrationHelpers, which include code to make column changes in ways that Postgres can do without locking. In general, this involves creating a new column, adding an index and any foreign keys as appropriate, adding a trigger to keep it populated alongside the old column, and then progressively copying data over to the new column, before removing the old column and replacing it with the new one. A few changes to GitLab's MigrationHelpers were necessary: * Some changes were made to remove dependencies on other GitLab code. * We explicitly wait for index creation before forging ahead on column replacements. * We use different temporary column names, to avoid running into index name length limits. * We rename the generated indices back to what they "should" be after replacing columns. * We rename the generated foreign keys to use the new column names when we had to create them. (This allows the migration to be rolled back without incident.) # Big Scary Warning There are two things here that may trip up large instances: 1. The change for tables' "id" columns is not concurrent. In particular, the stream_entries table may be big, and does not concurrently migrate its id column. (On the other hand, x_id type columns are all concurrent.) 2. This migration will take a long time to run, *but it should not lock tables during that time* (with the exception of the "id" columns as described above). That means this should probably be run in `screen` or some other session that can be run for a long time. Notably, the migration will take *longer* than it would without these changes, but the website will still be responsive during that time. These changes were tested on a relatively large statuses table (256k entries), and the service remained responsive during the migration. Migrations both forward and backward were tested. * Rubocop fixes * MigrationHelpers: Support ID columns in some cases This doesn't work in cases where the ID column is referred to as a foreign key by another table. * MigrationHelpers: support foreign keys for ID cols Note that this does not yet support foreign keys on non-primary-key columns, but Mastodon also doesn't yet have any that we've needed to migrate. This means we can perform fully "concurrent" migrations to change ID column types, and the IdsToBigints migration can happen with effectively no downtime. (A few operations require a transaction, such as renaming columns or deleting them, but these transactions should not block for noticeable amounts of time.) The algorithm for generating foreign key names has changed with this, and therefore all of those changed in schema.rb. * Provide status, allow for interruptions The MigrationHelpers now allow restarting the rename of a column if it was interrupted, by removing the old "new column" and re-starting the process. Along with this, they now provide status updates on the changes which are happening, as well as indications about when the changes can be safely interrupted (when there are at least 10 seconds estimated to be left before copying data is complete). The IdsToBigints migration now also sorts the columns it migrates by size, starting with the largest tables. This should provide administrators a worst-case scenario estimate for the length of migrations: each successive change will get faster, giving admins a chance to abort early on if they need to run the migration later. The idea is that this does not force them to try to time interruptions between smaller migrations. * Fix column sorting in IdsToBigints Not a significant change, but it impacts the order of columns in the database and db/schema.rb. * Actually pause before IdsToBigints --- app/models/account_domain_block.rb | 4 +- app/models/block.rb | 6 +- app/models/conversation_mute.rb | 4 +- app/models/domain_block.rb | 2 +- app/models/favourite.rb | 6 +- app/models/follow.rb | 6 +- app/models/follow_request.rb | 6 +- app/models/import.rb | 4 +- app/models/mention.rb | 4 +- app/models/mute.rb | 6 +- app/models/report.rb | 6 +- app/models/setting.rb | 4 +- app/models/stream_entry.rb | 5 +- app/models/subscription.rb | 4 +- app/models/web/setting.rb | 4 +- db/migrate/20170918125918_ids_to_bigints.rb | 232 ++++--- db/schema.rb | 134 ++-- lib/mastodon/migration_helpers.rb | 988 ++++++++++++++++++++++++++++ 18 files changed, 1202 insertions(+), 223 deletions(-) create mode 100644 lib/mastodon/migration_helpers.rb (limited to 'db') diff --git a/app/models/account_domain_block.rb b/app/models/account_domain_block.rb index bdd64c01a..fb695e473 100644 --- a/app/models/account_domain_block.rb +++ b/app/models/account_domain_block.rb @@ -3,11 +3,11 @@ # # Table name: account_domain_blocks # -# id :integer not null, primary key -# account_id :integer # domain :string # created_at :datetime not null # updated_at :datetime not null +# account_id :integer +# id :integer not null, primary key # class AccountDomainBlock < ApplicationRecord diff --git a/app/models/block.rb b/app/models/block.rb index edb0d2d11..a913782ed 100644 --- a/app/models/block.rb +++ b/app/models/block.rb @@ -3,11 +3,11 @@ # # Table name: blocks # -# id :integer not null, primary key -# account_id :integer not null -# target_account_id :integer not null # created_at :datetime not null # updated_at :datetime not null +# account_id :integer not null +# id :integer not null, primary key +# target_account_id :integer not null # class Block < ApplicationRecord diff --git a/app/models/conversation_mute.rb b/app/models/conversation_mute.rb index 79299b995..8d2399adf 100644 --- a/app/models/conversation_mute.rb +++ b/app/models/conversation_mute.rb @@ -3,9 +3,9 @@ # # Table name: conversation_mutes # -# id :integer not null, primary key -# account_id :integer not null # conversation_id :integer not null +# account_id :integer not null +# id :integer not null, primary key # class ConversationMute < ApplicationRecord diff --git a/app/models/domain_block.rb b/app/models/domain_block.rb index aea8919af..1268290bc 100644 --- a/app/models/domain_block.rb +++ b/app/models/domain_block.rb @@ -3,12 +3,12 @@ # # Table name: domain_blocks # -# id :integer not null, primary key # domain :string default(""), not null # created_at :datetime not null # updated_at :datetime not null # severity :integer default("silence") # reject_media :boolean default(FALSE), not null +# id :integer not null, primary key # class DomainBlock < ApplicationRecord diff --git a/app/models/favourite.rb b/app/models/favourite.rb index 53c79ccea..d28d5c05b 100644 --- a/app/models/favourite.rb +++ b/app/models/favourite.rb @@ -3,11 +3,11 @@ # # Table name: favourites # -# id :integer not null, primary key -# account_id :integer not null -# status_id :integer not null # created_at :datetime not null # updated_at :datetime not null +# account_id :integer not null +# id :integer not null, primary key +# status_id :integer not null # class Favourite < ApplicationRecord diff --git a/app/models/follow.rb b/app/models/follow.rb index 62f6fb670..667720a88 100644 --- a/app/models/follow.rb +++ b/app/models/follow.rb @@ -3,11 +3,11 @@ # # Table name: follows # -# id :integer not null, primary key -# account_id :integer not null -# target_account_id :integer not null # created_at :datetime not null # updated_at :datetime not null +# account_id :integer not null +# id :integer not null, primary key +# target_account_id :integer not null # class Follow < ApplicationRecord diff --git a/app/models/follow_request.rb b/app/models/follow_request.rb index 458c3a2cd..60036d903 100644 --- a/app/models/follow_request.rb +++ b/app/models/follow_request.rb @@ -3,11 +3,11 @@ # # Table name: follow_requests # -# id :integer not null, primary key -# account_id :integer not null -# target_account_id :integer not null # created_at :datetime not null # updated_at :datetime not null +# account_id :integer not null +# id :integer not null, primary key +# target_account_id :integer not null # class FollowRequest < ApplicationRecord diff --git a/app/models/import.rb b/app/models/import.rb index 4656c3af6..8ae7e3a46 100644 --- a/app/models/import.rb +++ b/app/models/import.rb @@ -3,8 +3,6 @@ # # Table name: imports # -# id :integer not null, primary key -# account_id :integer not null # type :integer not null # approved :boolean default(FALSE), not null # created_at :datetime not null @@ -13,6 +11,8 @@ # data_content_type :string # data_file_size :integer # data_updated_at :datetime +# account_id :integer not null +# id :integer not null, primary key # class Import < ApplicationRecord diff --git a/app/models/mention.rb b/app/models/mention.rb index 7450b1b85..3700c781c 100644 --- a/app/models/mention.rb +++ b/app/models/mention.rb @@ -3,11 +3,11 @@ # # Table name: mentions # -# id :integer not null, primary key -# account_id :integer # status_id :integer # created_at :datetime not null # updated_at :datetime not null +# account_id :integer +# id :integer not null, primary key # class Mention < ApplicationRecord diff --git a/app/models/mute.rb b/app/models/mute.rb index 00e5661a7..6e64848c7 100644 --- a/app/models/mute.rb +++ b/app/models/mute.rb @@ -3,11 +3,11 @@ # # Table name: mutes # -# id :integer not null, primary key -# account_id :integer not null -# target_account_id :integer not null # created_at :datetime not null # updated_at :datetime not null +# account_id :integer not null +# id :integer not null, primary key +# target_account_id :integer not null # class Mute < ApplicationRecord diff --git a/app/models/report.rb b/app/models/report.rb index 479aa17bb..bffb42b48 100644 --- a/app/models/report.rb +++ b/app/models/report.rb @@ -3,15 +3,15 @@ # # Table name: reports # -# id :integer not null, primary key -# account_id :integer not null -# target_account_id :integer not null # status_ids :integer default([]), not null, is an Array # comment :text default(""), not null # action_taken :boolean default(FALSE), not null # created_at :datetime not null # updated_at :datetime not null +# account_id :integer not null # action_taken_by_account_id :integer +# id :integer not null, primary key +# target_account_id :integer not null # class Report < ApplicationRecord diff --git a/app/models/setting.rb b/app/models/setting.rb index 340552581..a14f156a1 100644 --- a/app/models/setting.rb +++ b/app/models/setting.rb @@ -3,13 +3,13 @@ # # Table name: settings # -# id :integer not null, primary key # var :string not null # value :text # thing_type :string -# thing_id :integer # created_at :datetime # updated_at :datetime +# id :integer not null, primary key +# thing_id :integer # class Setting < RailsSettings::Base diff --git a/app/models/stream_entry.rb b/app/models/stream_entry.rb index 44aac39b3..b51fe9ad7 100644 --- a/app/models/stream_entry.rb +++ b/app/models/stream_entry.rb @@ -1,16 +1,15 @@ # frozen_string_literal: true - # == Schema Information # # Table name: stream_entries # -# id :integer not null, primary key -# account_id :integer # activity_id :integer # activity_type :string # created_at :datetime not null # updated_at :datetime not null # hidden :boolean default(FALSE), not null +# account_id :integer +# id :integer not null, primary key # class StreamEntry < ApplicationRecord diff --git a/app/models/subscription.rb b/app/models/subscription.rb index 14f1a140c..39860196b 100644 --- a/app/models/subscription.rb +++ b/app/models/subscription.rb @@ -3,16 +3,16 @@ # # Table name: subscriptions # -# id :integer not null, primary key # callback_url :string default(""), not null # secret :string # expires_at :datetime # confirmed :boolean default(FALSE), not null -# account_id :integer not null # created_at :datetime not null # updated_at :datetime not null # last_successful_delivery_at :datetime # domain :string +# account_id :integer not null +# id :integer not null, primary key # class Subscription < ApplicationRecord diff --git a/app/models/web/setting.rb b/app/models/web/setting.rb index 04a049523..1b0bfb2b7 100644 --- a/app/models/web/setting.rb +++ b/app/models/web/setting.rb @@ -3,11 +3,11 @@ # # Table name: web_settings # -# id :integer not null, primary key -# user_id :integer # data :json # created_at :datetime not null # updated_at :datetime not null +# id :integer not null, primary key +# user_id :integer # class Web::Setting < ApplicationRecord diff --git a/db/migrate/20170918125918_ids_to_bigints.rb b/db/migrate/20170918125918_ids_to_bigints.rb index 7483dd77a..c6feed8f9 100644 --- a/db/migrate/20170918125918_ids_to_bigints.rb +++ b/db/migrate/20170918125918_ids_to_bigints.rb @@ -1,127 +1,119 @@ +require Rails.root.join('lib', 'mastodon', 'migration_helpers') + class IdsToBigints < ActiveRecord::Migration[5.1] + include Mastodon::MigrationHelpers + + disable_ddl_transaction! + + INCLUDED_COLUMNS = [ + [:account_domain_blocks, :account_id], + [:account_domain_blocks, :id], + [:accounts, :id], + [:blocks, :account_id], + [:blocks, :id], + [:blocks, :target_account_id], + [:conversation_mutes, :account_id], + [:conversation_mutes, :id], + [:domain_blocks, :id], + [:favourites, :account_id], + [:favourites, :id], + [:favourites, :status_id], + [:follow_requests, :account_id], + [:follow_requests, :id], + [:follow_requests, :target_account_id], + [:follows, :account_id], + [:follows, :id], + [:follows, :target_account_id], + [:imports, :account_id], + [:imports, :id], + [:media_attachments, :account_id], + [:media_attachments, :id], + [:mentions, :account_id], + [:mentions, :id], + [:mutes, :account_id], + [:mutes, :id], + [:mutes, :target_account_id], + [:notifications, :account_id], + [:notifications, :from_account_id], + [:notifications, :id], + [:oauth_access_grants, :application_id], + [:oauth_access_grants, :id], + [:oauth_access_grants, :resource_owner_id], + [:oauth_access_tokens, :application_id], + [:oauth_access_tokens, :id], + [:oauth_access_tokens, :resource_owner_id], + [:oauth_applications, :id], + [:oauth_applications, :owner_id], + [:reports, :account_id], + [:reports, :action_taken_by_account_id], + [:reports, :id], + [:reports, :target_account_id], + [:session_activations, :access_token_id], + [:session_activations, :user_id], + [:session_activations, :web_push_subscription_id], + [:settings, :id], + [:settings, :thing_id], + [:statuses, :account_id], + [:statuses, :application_id], + [:statuses, :in_reply_to_account_id], + [:stream_entries, :account_id], + [:stream_entries, :id], + [:subscriptions, :account_id], + [:subscriptions, :id], + [:tags, :id], + [:users, :account_id], + [:users, :id], + [:web_settings, :id], + [:web_settings, :user_id], + ] + INCLUDED_COLUMNS << [:deprecated_preview_cards, :id] if table_exists?(:deprecated_preview_cards) + + def migrate_columns(to_type) + # Print out a warning that this will probably take a while. + say '' + say 'WARNING: This migration may take a *long* time for large instances' + say 'It will *not* lock tables for any significant time, but it may run' + say 'for a very long time. We will pause for 10 seconds to allow you to' + say 'interrupt this migration if you are not ready.' + say '' + say 'This migration has some sections that can be safely interrupted' + say 'and restarted later, and will tell you when those are occurring.' + say '' + say 'For more information, see https://github.com/tootsuite/mastodon/pull/5088' + + 10.downto(1) do |i| + say "Continuing in #{i} second#{i == 1 ? '' : 's'}...", true + sleep 1 + end + + tables = INCLUDED_COLUMNS.map(&:first).uniq + table_sizes = {} + + # Sort tables by their size + tables.each do |table| + table_sizes[table] = estimate_rows_in_table(table) + end + + ordered_columns = INCLUDED_COLUMNS.sort_by do |col_parts| + [-table_sizes[col_parts.first], col_parts.last] + end + + ordered_columns.each do |column_parts| + table, column = column_parts + + # Skip this if we're resuming and already did this one. + next if column_for(table, column).sql_type == to_type.to_s + + change_column_type_concurrently table, column, to_type + cleanup_concurrent_column_type_change table, column + end + end + def up - change_column :account_domain_blocks, :account_id, :bigint - change_column :account_domain_blocks, :id, :bigint - change_column :accounts, :id, :bigint - change_column :blocks, :account_id, :bigint - change_column :blocks, :id, :bigint - change_column :blocks, :target_account_id, :bigint - change_column :conversation_mutes, :account_id, :bigint - change_column :conversation_mutes, :id, :bigint - change_column :deprecated_preview_cards, :id, :bigint if table_exists?(:deprecated_preview_cards) - change_column :domain_blocks, :id, :bigint - change_column :favourites, :account_id, :bigint - change_column :favourites, :id, :bigint - change_column :favourites, :status_id, :bigint - change_column :follow_requests, :account_id, :bigint - change_column :follow_requests, :id, :bigint - change_column :follow_requests, :target_account_id, :bigint - change_column :follows, :account_id, :bigint - change_column :follows, :id, :bigint - change_column :follows, :target_account_id, :bigint - change_column :imports, :account_id, :bigint - change_column :imports, :id, :bigint - change_column :media_attachments, :account_id, :bigint - change_column :media_attachments, :id, :bigint - change_column :mentions, :account_id, :bigint - change_column :mentions, :id, :bigint - change_column :mutes, :account_id, :bigint - change_column :mutes, :id, :bigint - change_column :mutes, :target_account_id, :bigint - change_column :notifications, :account_id, :bigint - change_column :notifications, :from_account_id, :bigint - change_column :notifications, :id, :bigint - change_column :oauth_access_grants, :application_id, :bigint - change_column :oauth_access_grants, :id, :bigint - change_column :oauth_access_grants, :resource_owner_id, :bigint - change_column :oauth_access_tokens, :application_id, :bigint - change_column :oauth_access_tokens, :id, :bigint - change_column :oauth_access_tokens, :resource_owner_id, :bigint - change_column :oauth_applications, :id, :bigint - change_column :oauth_applications, :owner_id, :bigint - change_column :reports, :account_id, :bigint - change_column :reports, :action_taken_by_account_id, :bigint - change_column :reports, :id, :bigint - change_column :reports, :target_account_id, :bigint - change_column :session_activations, :access_token_id, :bigint - change_column :session_activations, :user_id, :bigint - change_column :session_activations, :web_push_subscription_id, :bigint - change_column :settings, :id, :bigint - change_column :settings, :thing_id, :bigint - change_column :statuses, :account_id, :bigint - change_column :statuses, :application_id, :bigint - change_column :statuses, :in_reply_to_account_id, :bigint - change_column :stream_entries, :account_id, :bigint - change_column :stream_entries, :id, :bigint - change_column :subscriptions, :account_id, :bigint - change_column :subscriptions, :id, :bigint - change_column :tags, :id, :bigint - change_column :users, :account_id, :bigint - change_column :users, :id, :bigint - change_column :web_settings, :id, :bigint - change_column :web_settings, :user_id, :bigint + migrate_columns(:bigint) end def down - change_column :account_domain_blocks, :account_id, :integer - change_column :account_domain_blocks, :id, :integer - change_column :accounts, :id, :integer - change_column :blocks, :account_id, :integer - change_column :blocks, :id, :integer - change_column :blocks, :target_account_id, :integer - change_column :conversation_mutes, :account_id, :integer - change_column :conversation_mutes, :id, :integer - change_column :deprecated_preview_cards, :id, :integer if table_exists?(:deprecated_preview_cards) - change_column :domain_blocks, :id, :integer - change_column :favourites, :account_id, :integer - change_column :favourites, :id, :integer - change_column :favourites, :status_id, :integer - change_column :follow_requests, :account_id, :integer - change_column :follow_requests, :id, :integer - change_column :follow_requests, :target_account_id, :integer - change_column :follows, :account_id, :integer - change_column :follows, :id, :integer - change_column :follows, :target_account_id, :integer - change_column :imports, :account_id, :integer - change_column :imports, :id, :integer - change_column :media_attachments, :account_id, :integer - change_column :media_attachments, :id, :integer - change_column :mentions, :account_id, :integer - change_column :mentions, :id, :integer - change_column :mutes, :account_id, :integer - change_column :mutes, :id, :integer - change_column :mutes, :target_account_id, :integer - change_column :notifications, :account_id, :integer - change_column :notifications, :from_account_id, :integer - change_column :notifications, :id, :integer - change_column :oauth_access_grants, :application_id, :integer - change_column :oauth_access_grants, :id, :integer - change_column :oauth_access_grants, :resource_owner_id, :integer - change_column :oauth_access_tokens, :application_id, :integer - change_column :oauth_access_tokens, :id, :integer - change_column :oauth_access_tokens, :resource_owner_id, :integer - change_column :oauth_applications, :id, :integer - change_column :oauth_applications, :owner_id, :integer - change_column :reports, :account_id, :integer - change_column :reports, :action_taken_by_account_id, :integer - change_column :reports, :id, :integer - change_column :reports, :target_account_id, :integer - change_column :session_activations, :access_token_id, :integer - change_column :session_activations, :user_id, :integer - change_column :session_activations, :web_push_subscription_id, :integer - change_column :settings, :id, :integer - change_column :settings, :thing_id, :integer - change_column :statuses, :account_id, :integer - change_column :statuses, :application_id, :integer - change_column :statuses, :in_reply_to_account_id, :integer - change_column :stream_entries, :account_id, :integer - change_column :stream_entries, :id, :integer - change_column :subscriptions, :account_id, :integer - change_column :subscriptions, :id, :integer - change_column :tags, :id, :integer - change_column :users, :account_id, :integer - change_column :users, :id, :integer - change_column :web_settings, :id, :integer - change_column :web_settings, :user_id, :integer + migrate_columns(:integer) end end diff --git a/db/schema.rb b/db/schema.rb index 90f8a5683..2cb105553 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -16,10 +16,10 @@ ActiveRecord::Schema.define(version: 20170927215609) do enable_extension "plpgsql" create_table "account_domain_blocks", force: :cascade do |t| - t.bigint "account_id" t.string "domain" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id" t.index ["account_id", "domain"], name: "index_account_domain_blocks_on_account_id_and_domain", unique: true end @@ -69,16 +69,16 @@ ActiveRecord::Schema.define(version: 20170927215609) do end create_table "blocks", force: :cascade do |t| - t.bigint "account_id", null: false - t.bigint "target_account_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id", null: false + t.bigint "target_account_id", null: false t.index ["account_id", "target_account_id"], name: "index_blocks_on_account_id_and_target_account_id", unique: true end create_table "conversation_mutes", force: :cascade do |t| - t.bigint "account_id", null: false t.bigint "conversation_id", null: false + t.bigint "account_id", null: false t.index ["account_id", "conversation_id"], name: "index_conversation_mutes_on_account_id_and_conversation_id", unique: true end @@ -111,33 +111,32 @@ ActiveRecord::Schema.define(version: 20170927215609) do end create_table "favourites", force: :cascade do |t| - t.bigint "account_id", null: false - t.bigint "status_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id", null: false + t.bigint "status_id", null: false t.index ["account_id", "id"], name: "index_favourites_on_account_id_and_id" t.index ["account_id", "status_id"], name: "index_favourites_on_account_id_and_status_id", unique: true t.index ["status_id"], name: "index_favourites_on_status_id" end create_table "follow_requests", force: :cascade do |t| - t.bigint "account_id", null: false - t.bigint "target_account_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id", null: false + t.bigint "target_account_id", null: false t.index ["account_id", "target_account_id"], name: "index_follow_requests_on_account_id_and_target_account_id", unique: true end create_table "follows", force: :cascade do |t| - t.bigint "account_id", null: false - t.bigint "target_account_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id", null: false + t.bigint "target_account_id", null: false t.index ["account_id", "target_account_id"], name: "index_follows_on_account_id_and_target_account_id", unique: true end create_table "imports", force: :cascade do |t| - t.bigint "account_id", null: false t.integer "type", null: false t.boolean "approved", default: false, null: false t.datetime "created_at", null: false @@ -146,6 +145,7 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.string "data_content_type" t.integer "data_file_size" t.datetime "data_updated_at" + t.bigint "account_id", null: false end create_table "media_attachments", force: :cascade do |t| @@ -155,12 +155,12 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.integer "file_file_size" t.datetime "file_updated_at" t.string "remote_url", default: "", null: false - t.bigint "account_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "shortcode" t.integer "type", default: 0, null: false t.json "file_meta" + t.bigint "account_id" t.text "description" t.index ["account_id"], name: "index_media_attachments_on_account_id" t.index ["shortcode"], name: "index_media_attachments_on_shortcode", unique: true @@ -168,28 +168,28 @@ ActiveRecord::Schema.define(version: 20170927215609) do end create_table "mentions", force: :cascade do |t| - t.bigint "account_id" t.bigint "status_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id" t.index ["account_id", "status_id"], name: "index_mentions_on_account_id_and_status_id", unique: true t.index ["status_id"], name: "index_mentions_on_status_id" end create_table "mutes", force: :cascade do |t| - t.bigint "account_id", null: false - t.bigint "target_account_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id", null: false + t.bigint "target_account_id", null: false t.index ["account_id", "target_account_id"], name: "index_mutes_on_account_id_and_target_account_id", unique: true end create_table "notifications", force: :cascade do |t| - t.bigint "account_id" t.bigint "activity_id" t.string "activity_type" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id" t.bigint "from_account_id" t.index ["account_id", "activity_id", "activity_type"], name: "account_activity", unique: true t.index ["activity_id", "activity_type"], name: "index_notifications_on_activity_id_and_activity_type" @@ -197,26 +197,26 @@ ActiveRecord::Schema.define(version: 20170927215609) do end create_table "oauth_access_grants", force: :cascade do |t| - t.bigint "resource_owner_id", null: false - t.bigint "application_id", null: false t.string "token", null: false t.integer "expires_in", null: false t.text "redirect_uri", null: false t.datetime "created_at", null: false t.datetime "revoked_at" t.string "scopes" + t.bigint "application_id", null: false + t.bigint "resource_owner_id", null: false t.index ["token"], name: "index_oauth_access_grants_on_token", unique: true end create_table "oauth_access_tokens", force: :cascade do |t| - t.bigint "resource_owner_id" - t.bigint "application_id" t.string "token", null: false t.string "refresh_token" t.integer "expires_in" t.datetime "revoked_at" t.datetime "created_at", null: false t.string "scopes" + t.bigint "application_id" + t.bigint "resource_owner_id" t.index ["refresh_token"], name: "index_oauth_access_tokens_on_refresh_token", unique: true t.index ["resource_owner_id"], name: "index_oauth_access_tokens_on_resource_owner_id" t.index ["token"], name: "index_oauth_access_tokens_on_token", unique: true @@ -232,8 +232,8 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.datetime "updated_at" t.boolean "superapp", default: false, null: false t.string "website" - t.bigint "owner_id" t.string "owner_type" + t.bigint "owner_id" t.index ["owner_id", "owner_type"], name: "index_oauth_applications_on_owner_id_and_owner_type" t.index ["uid"], name: "index_oauth_applications_on_uid", unique: true end @@ -266,26 +266,26 @@ ActiveRecord::Schema.define(version: 20170927215609) do end create_table "reports", force: :cascade do |t| - t.bigint "account_id", null: false - t.bigint "target_account_id", null: false t.bigint "status_ids", default: [], null: false, array: true t.text "comment", default: "", null: false t.boolean "action_taken", default: false, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "account_id", null: false t.bigint "action_taken_by_account_id" + t.bigint "target_account_id", null: false t.index ["account_id"], name: "index_reports_on_account_id" t.index ["target_account_id"], name: "index_reports_on_target_account_id" end create_table "session_activations", force: :cascade do |t| - t.bigint "user_id", null: false t.string "session_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "user_agent", default: "", null: false t.inet "ip" t.bigint "access_token_id" + t.bigint "user_id", null: false t.bigint "web_push_subscription_id" t.index ["session_id"], name: "index_session_activations_on_session_id", unique: true t.index ["user_id"], name: "index_session_activations_on_user_id" @@ -295,9 +295,9 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.string "var", null: false t.text "value" t.string "thing_type" - t.bigint "thing_id" t.datetime "created_at" t.datetime "updated_at" + t.bigint "thing_id" t.index ["thing_type", "thing_id", "var"], name: "index_settings_on_thing_type_and_thing_id_and_var", unique: true end @@ -323,7 +323,6 @@ ActiveRecord::Schema.define(version: 20170927215609) do create_table "statuses", force: :cascade do |t| t.string "uri" - t.bigint "account_id", null: false t.text "text", default: "", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false @@ -332,8 +331,6 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.string "url" t.boolean "sensitive", default: false, null: false t.integer "visibility", default: 0, null: false - t.bigint "in_reply_to_account_id" - t.bigint "application_id" t.text "spoiler_text", default: "", null: false t.boolean "reply", default: false, null: false t.integer "favourites_count", default: 0, null: false @@ -341,6 +338,9 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.string "language" t.bigint "conversation_id" t.boolean "local" + t.bigint "account_id", null: false + t.bigint "application_id" + t.bigint "in_reply_to_account_id" t.index ["account_id", "id"], name: "index_statuses_on_account_id_id" t.index ["conversation_id"], name: "index_statuses_on_conversation_id" t.index ["in_reply_to_id"], name: "index_statuses_on_in_reply_to_id" @@ -356,12 +356,12 @@ ActiveRecord::Schema.define(version: 20170927215609) do end create_table "stream_entries", force: :cascade do |t| - t.bigint "account_id" t.bigint "activity_id" t.string "activity_type" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.boolean "hidden", default: false, null: false + t.bigint "account_id" t.index ["account_id"], name: "index_stream_entries_on_account_id" t.index ["activity_id", "activity_type"], name: "index_stream_entries_on_activity_id_and_activity_type" end @@ -371,11 +371,11 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.string "secret" t.datetime "expires_at" t.boolean "confirmed", default: false, null: false - t.bigint "account_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "last_successful_delivery_at" t.string "domain" + t.bigint "account_id", null: false t.index ["account_id", "callback_url"], name: "index_subscriptions_on_account_id_and_callback_url", unique: true end @@ -389,7 +389,6 @@ ActiveRecord::Schema.define(version: 20170927215609) do create_table "users", force: :cascade do |t| t.string "email", default: "", null: false - t.bigint "account_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "encrypted_password", default: "", null: false @@ -415,6 +414,7 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.datetime "last_emailed_at" t.string "otp_backup_codes", array: true t.string "filtered_languages", default: [], null: false, array: true + t.bigint "account_id", null: false t.index ["account_id"], name: "index_users_on_account_id" t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true t.index ["email"], name: "index_users_on_email", unique: true @@ -432,53 +432,53 @@ ActiveRecord::Schema.define(version: 20170927215609) do end create_table "web_settings", force: :cascade do |t| - t.bigint "user_id" t.json "data" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.bigint "user_id" t.index ["user_id"], name: "index_web_settings_on_user_id", unique: true end - add_foreign_key "account_domain_blocks", "accounts", on_delete: :cascade - add_foreign_key "blocks", "accounts", column: "target_account_id", on_delete: :cascade - add_foreign_key "blocks", "accounts", on_delete: :cascade - add_foreign_key "conversation_mutes", "accounts", on_delete: :cascade + add_foreign_key "account_domain_blocks", "accounts", name: "fk_206c6029bd", on_delete: :cascade + add_foreign_key "blocks", "accounts", column: "target_account_id", name: "fk_9571bfabc1", on_delete: :cascade + add_foreign_key "blocks", "accounts", name: "fk_4269e03e65", on_delete: :cascade + add_foreign_key "conversation_mutes", "accounts", name: "fk_225b4212bb", on_delete: :cascade add_foreign_key "conversation_mutes", "conversations", on_delete: :cascade - add_foreign_key "favourites", "accounts", on_delete: :cascade - add_foreign_key "favourites", "statuses", on_delete: :cascade - add_foreign_key "follow_requests", "accounts", column: "target_account_id", on_delete: :cascade - add_foreign_key "follow_requests", "accounts", on_delete: :cascade - add_foreign_key "follows", "accounts", column: "target_account_id", on_delete: :cascade - add_foreign_key "follows", "accounts", on_delete: :cascade - add_foreign_key "imports", "accounts", on_delete: :cascade - add_foreign_key "media_attachments", "accounts", on_delete: :nullify + add_foreign_key "favourites", "accounts", name: "fk_5eb6c2b873", on_delete: :cascade + add_foreign_key "favourites", "statuses", name: "fk_b0e856845e", on_delete: :cascade + add_foreign_key "follow_requests", "accounts", column: "target_account_id", name: "fk_9291ec025d", on_delete: :cascade + add_foreign_key "follow_requests", "accounts", name: "fk_76d644b0e7", on_delete: :cascade + add_foreign_key "follows", "accounts", column: "target_account_id", name: "fk_745ca29eac", on_delete: :cascade + add_foreign_key "follows", "accounts", name: "fk_32ed1b5560", on_delete: :cascade + add_foreign_key "imports", "accounts", name: "fk_6db1b6e408", on_delete: :cascade + add_foreign_key "media_attachments", "accounts", name: "fk_96dd81e81b", on_delete: :nullify add_foreign_key "media_attachments", "statuses", on_delete: :nullify - add_foreign_key "mentions", "accounts", on_delete: :cascade + add_foreign_key "mentions", "accounts", name: "fk_970d43f9d1", on_delete: :cascade add_foreign_key "mentions", "statuses", on_delete: :cascade - add_foreign_key "mutes", "accounts", column: "target_account_id", on_delete: :cascade - add_foreign_key "mutes", "accounts", on_delete: :cascade - add_foreign_key "notifications", "accounts", column: "from_account_id", on_delete: :cascade - add_foreign_key "notifications", "accounts", on_delete: :cascade - add_foreign_key "oauth_access_grants", "oauth_applications", column: "application_id", on_delete: :cascade - add_foreign_key "oauth_access_grants", "users", column: "resource_owner_id", on_delete: :cascade - add_foreign_key "oauth_access_tokens", "oauth_applications", column: "application_id", on_delete: :cascade - add_foreign_key "oauth_access_tokens", "users", column: "resource_owner_id", on_delete: :cascade - add_foreign_key "oauth_applications", "users", column: "owner_id", on_delete: :cascade - add_foreign_key "reports", "accounts", column: "action_taken_by_account_id", on_delete: :nullify - add_foreign_key "reports", "accounts", column: "target_account_id", on_delete: :cascade - add_foreign_key "reports", "accounts", on_delete: :cascade - add_foreign_key "session_activations", "oauth_access_tokens", column: "access_token_id", on_delete: :cascade - add_foreign_key "session_activations", "users", on_delete: :cascade - add_foreign_key "status_pins", "accounts", on_delete: :cascade + add_foreign_key "mutes", "accounts", column: "target_account_id", name: "fk_eecff219ea", on_delete: :cascade + add_foreign_key "mutes", "accounts", name: "fk_b8d8daf315", on_delete: :cascade + add_foreign_key "notifications", "accounts", column: "from_account_id", name: "fk_fbd6b0bf9e", on_delete: :cascade + add_foreign_key "notifications", "accounts", name: "fk_c141c8ee55", on_delete: :cascade + add_foreign_key "oauth_access_grants", "oauth_applications", column: "application_id", name: "fk_34d54b0a33", on_delete: :cascade + add_foreign_key "oauth_access_grants", "users", column: "resource_owner_id", name: "fk_63b044929b", on_delete: :cascade + add_foreign_key "oauth_access_tokens", "oauth_applications", column: "application_id", name: "fk_f5fc4c1ee3", on_delete: :cascade + add_foreign_key "oauth_access_tokens", "users", column: "resource_owner_id", name: "fk_e84df68546", on_delete: :cascade + add_foreign_key "oauth_applications", "users", column: "owner_id", name: "fk_b0988c7c0a", on_delete: :cascade + add_foreign_key "reports", "accounts", column: "action_taken_by_account_id", name: "fk_bca45b75fd", on_delete: :nullify + add_foreign_key "reports", "accounts", column: "target_account_id", name: "fk_eb37af34f0", on_delete: :cascade + add_foreign_key "reports", "accounts", name: "fk_4b81f7522c", on_delete: :cascade + add_foreign_key "session_activations", "oauth_access_tokens", column: "access_token_id", name: "fk_957e5bda89", on_delete: :cascade + add_foreign_key "session_activations", "users", name: "fk_e5fda67334", on_delete: :cascade + add_foreign_key "status_pins", "accounts", name: "fk_d4cb435b62", on_delete: :cascade add_foreign_key "status_pins", "statuses", on_delete: :cascade - add_foreign_key "statuses", "accounts", column: "in_reply_to_account_id", on_delete: :nullify - add_foreign_key "statuses", "accounts", on_delete: :cascade + add_foreign_key "statuses", "accounts", column: "in_reply_to_account_id", name: "fk_c7fa917661", on_delete: :nullify + add_foreign_key "statuses", "accounts", name: "fk_9bda1543f7", on_delete: :cascade add_foreign_key "statuses", "statuses", column: "in_reply_to_id", on_delete: :nullify add_foreign_key "statuses", "statuses", column: "reblog_of_id", on_delete: :cascade add_foreign_key "statuses_tags", "statuses", on_delete: :cascade - add_foreign_key "statuses_tags", "tags", on_delete: :cascade - add_foreign_key "stream_entries", "accounts", on_delete: :cascade - add_foreign_key "subscriptions", "accounts", on_delete: :cascade - add_foreign_key "users", "accounts", on_delete: :cascade - add_foreign_key "web_settings", "users", on_delete: :cascade + add_foreign_key "statuses_tags", "tags", name: "fk_3081861e21", on_delete: :cascade + add_foreign_key "stream_entries", "accounts", name: "fk_5659b17554", on_delete: :cascade + add_foreign_key "subscriptions", "accounts", name: "fk_9847d1cbb5", on_delete: :cascade + add_foreign_key "users", "accounts", name: "fk_50500f500d", on_delete: :cascade + add_foreign_key "web_settings", "users", name: "fk_11910667b2", on_delete: :cascade end diff --git a/lib/mastodon/migration_helpers.rb b/lib/mastodon/migration_helpers.rb new file mode 100644 index 000000000..ed716501e --- /dev/null +++ b/lib/mastodon/migration_helpers.rb @@ -0,0 +1,988 @@ +# frozen_string_literal: true + +# This file is copied almost entirely from GitLab, which has done a large +# amount of work to ensure that migrations can happen with minimal downtime. +# Many thanks to those engineers. + +# Changes have been made to remove dependencies on other GitLab files and to +# shorten temporary column names. + +# Documentation on using these functions (and why one might do so): +# https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/development/what_requires_downtime.md + +# The file itself: +# https://gitlab.com/gitlab-org/gitlab-ce/blob/master/lib/gitlab/database/migration_helpers.rb + +# It is licensed as follows: + +# Copyright (c) 2011-2017 GitLab B.V. + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +# This is bad form, but there are enough differences that it's impractical to do +# otherwise: +# rubocop:disable all + +module Mastodon + module MigrationHelpers + # Stub for Database.postgresql? from GitLab + def self.postgresql? + ActiveRecord::Base.configurations[Rails.env]['adapter'].casecmp('postgresql').zero? + end + + # Stub for Database.mysql? from GitLab + def self.mysql? + ActiveRecord::Base.configurations[Rails.env]['adapter'].casecmp('mysql2').zero? + end + + # Model that can be used for querying permissions of a SQL user. + class Grant < ActiveRecord::Base + self.table_name = + if Mastodon::MigrationHelpers.postgresql? + 'information_schema.role_table_grants' + else + 'mysql.user' + end + + def self.scope_to_current_user + if Mastodon::MigrationHelpers.postgresql? + where('grantee = user') + else + where("CONCAT(User, '@', Host) = current_user()") + end + end + + # Returns true if the current user can create and execute triggers on the + # given table. + def self.create_and_execute_trigger?(table) + priv = + if Mastodon::MigrationHelpers.postgresql? + where(privilege_type: 'TRIGGER', table_name: table) + else + where(Trigger_priv: 'Y') + end + + priv.scope_to_current_user.any? + end + end + + BACKGROUND_MIGRATION_BATCH_SIZE = 1000 # Number of rows to process per job + BACKGROUND_MIGRATION_JOB_BUFFER_SIZE = 1000 # Number of jobs to bulk queue at a time + + # Gets an estimated number of rows for a table + def estimate_rows_in_table(table_name) + exec_query('SELECT reltuples FROM pg_class WHERE relname = ' + + "'#{table_name}'").to_a.first['reltuples'] + end + + # Adds `created_at` and `updated_at` columns with timezone information. + # + # This method is an improved version of Rails' built-in method `add_timestamps`. + # + # Available options are: + # default - The default value for the column. + # null - When set to `true` the column will allow NULL values. + # The default is to not allow NULL values. + def add_timestamps_with_timezone(table_name, options = {}) + options[:null] = false if options[:null].nil? + + [:created_at, :updated_at].each do |column_name| + if options[:default] && transaction_open? + raise '`add_timestamps_with_timezone` with default value cannot be run inside a transaction. ' \ + 'You can disable transactions by calling `disable_ddl_transaction!` ' \ + 'in the body of your migration class' + end + + # If default value is presented, use `add_column_with_default` method instead. + if options[:default] + add_column_with_default( + table_name, + column_name, + :datetime_with_timezone, + default: options[:default], + allow_null: options[:null] + ) + else + add_column(table_name, column_name, :datetime_with_timezone, options) + end + end + end + + # Creates a new index, concurrently when supported + # + # On PostgreSQL this method creates an index concurrently, on MySQL this + # creates a regular index. + # + # Example: + # + # add_concurrent_index :users, :some_column + # + # See Rails' `add_index` for more info on the available arguments. + def add_concurrent_index(table_name, column_name, options = {}) + if transaction_open? + raise 'add_concurrent_index can not be run inside a transaction, ' \ + 'you can disable transactions by calling disable_ddl_transaction! ' \ + 'in the body of your migration class' + end + + if MigrationHelpers.postgresql? + options = options.merge({ algorithm: :concurrently }) + disable_statement_timeout + end + + add_index(table_name, column_name, options) + end + + # Removes an existed index, concurrently when supported + # + # On PostgreSQL this method removes an index concurrently. + # + # Example: + # + # remove_concurrent_index :users, :some_column + # + # See Rails' `remove_index` for more info on the available arguments. + def remove_concurrent_index(table_name, column_name, options = {}) + if transaction_open? + raise 'remove_concurrent_index can not be run inside a transaction, ' \ + 'you can disable transactions by calling disable_ddl_transaction! ' \ + 'in the body of your migration class' + end + + if supports_drop_index_concurrently? + options = options.merge({ algorithm: :concurrently }) + disable_statement_timeout + end + + remove_index(table_name, options.merge({ column: column_name })) + end + + # Removes an existing index, concurrently when supported + # + # On PostgreSQL this method removes an index concurrently. + # + # Example: + # + # remove_concurrent_index :users, "index_X_by_Y" + # + # See Rails' `remove_index` for more info on the available arguments. + def remove_concurrent_index_by_name(table_name, index_name, options = {}) + if transaction_open? + raise 'remove_concurrent_index_by_name can not be run inside a transaction, ' \ + 'you can disable transactions by calling disable_ddl_transaction! ' \ + 'in the body of your migration class' + end + + if supports_drop_index_concurrently? + options = options.merge({ algorithm: :concurrently }) + disable_statement_timeout + end + + remove_index(table_name, options.merge({ name: index_name })) + end + + # Only available on Postgresql >= 9.2 + def supports_drop_index_concurrently? + return false unless MigrationHelpers.postgresql? + + version = select_one("SELECT current_setting('server_version_num') AS v")['v'].to_i + + version >= 90200 + end + + # Adds a foreign key with only minimal locking on the tables involved. + # + # This method only requires minimal locking when using PostgreSQL. When + # using MySQL this method will use Rails' default `add_foreign_key`. + # + # source - The source table containing the foreign key. + # target - The target table the key points to. + # column - The name of the column to create the foreign key on. + # on_delete - The action to perform when associated data is removed, + # defaults to "CASCADE". + def add_concurrent_foreign_key(source, target, column:, on_delete: :cascade, target_col: 'id') + # Transactions would result in ALTER TABLE locks being held for the + # duration of the transaction, defeating the purpose of this method. + if transaction_open? + raise 'add_concurrent_foreign_key can not be run inside a transaction' + end + + # While MySQL does allow disabling of foreign keys it has no equivalent + # of PostgreSQL's "VALIDATE CONSTRAINT". As a result we'll just fall + # back to the normal foreign key procedure. + if MigrationHelpers.mysql? + return add_foreign_key(source, target, + column: column, + on_delete: on_delete) + else + on_delete = 'SET NULL' if on_delete == :nullify + end + + disable_statement_timeout + + key_name = concurrent_foreign_key_name(source, column, target_col) + + # Using NOT VALID allows us to create a key without immediately + # validating it. This means we keep the ALTER TABLE lock only for a + # short period of time. The key _is_ enforced for any newly created + # data. + execute <<-EOF.strip_heredoc + ALTER TABLE #{source} + ADD CONSTRAINT #{key_name} + FOREIGN KEY (#{column}) + REFERENCES #{target} (#{target_col}) + #{on_delete ? "ON DELETE #{on_delete.upcase}" : ''} + NOT VALID; + EOF + + # Validate the existing constraint. This can potentially take a very + # long time to complete, but fortunately does not lock the source table + # while running. + execute("ALTER TABLE #{source} VALIDATE CONSTRAINT #{key_name};") + end + + # Returns the name for a concurrent foreign key. + # + # PostgreSQL constraint names have a limit of 63 bytes. The logic used + # here is based on Rails' foreign_key_name() method, which unfortunately + # is private so we can't rely on it directly. + def concurrent_foreign_key_name(table, column, target_col) + "fk_#{Digest::SHA256.hexdigest("#{table}_#{column}_#{target_col}_fk").first(10)}" + end + + # Long-running migrations may take more than the timeout allowed by + # the database. Disable the session's statement timeout to ensure + # migrations don't get killed prematurely. (PostgreSQL only) + def disable_statement_timeout + execute('SET statement_timeout TO 0') if MigrationHelpers.postgresql? + end + + # Updates the value of a column in batches. + # + # This method updates the table in batches of 5% of the total row count. + # This method will continue updating rows until no rows remain. + # + # When given a block this method will yield two values to the block: + # + # 1. An instance of `Arel::Table` for the table that is being updated. + # 2. The query to run as an Arel object. + # + # By supplying a block one can add extra conditions to the queries being + # executed. Note that the same block is used for _all_ queries. + # + # Example: + # + # update_column_in_batches(:projects, :foo, 10) do |table, query| + # query.where(table[:some_column].eq('hello')) + # end + # + # This would result in this method updating only rows where + # `projects.some_column` equals "hello". + # + # table - The name of the table. + # column - The name of the column to update. + # value - The value for the column. + # + # Rubocop's Metrics/AbcSize metric is disabled for this method as Rubocop + # determines this method to be too complex while there's no way to make it + # less "complex" without introducing extra methods (which actually will + # make things _more_ complex). + # + # rubocop: disable Metrics/AbcSize + def update_column_in_batches(table_name, column, value) + if transaction_open? + raise 'update_column_in_batches can not be run inside a transaction, ' \ + 'you can disable transactions by calling disable_ddl_transaction! ' \ + 'in the body of your migration class' + end + + table = Arel::Table.new(table_name) + + total = estimate_rows_in_table(table_name).to_i + if total == 0 + count_arel = table.project(Arel.star.count.as('count')) + count_arel = yield table, count_arel if block_given? + + total = exec_query(count_arel.to_sql).to_hash.first['count'].to_i + + return if total == 0 + end + + # Update in batches of 5% until we run out of any rows to update. + batch_size = ((total / 100.0) * 5.0).ceil + max_size = 1000 + + # The upper limit is 1000 to ensure we don't lock too many rows. For + # example, for "merge_requests" even 1% of the table is around 35 000 + # rows for GitLab.com. + batch_size = max_size if batch_size > max_size + + start_arel = table.project(table[:id]).order(table[:id].asc).take(1) + start_arel = yield table, start_arel if block_given? + start_id = exec_query(start_arel.to_sql).to_hash.first['id'].to_i + + say "Migrating #{table_name}.#{column} (~#{total.to_i} rows)" + + started_time = Time.now + last_time = Time.now + migrated = 0 + loop do + stop_row = nil + + suppress_messages do + stop_arel = table.project(table[:id]) + .where(table[:id].gteq(start_id)) + .order(table[:id].asc) + .take(1) + .skip(batch_size) + + stop_arel = yield table, stop_arel if block_given? + stop_row = exec_query(stop_arel.to_sql).to_hash.first + + update_arel = Arel::UpdateManager.new + .table(table) + .set([[table[column], value]]) + .where(table[:id].gteq(start_id)) + + if stop_row + stop_id = stop_row['id'].to_i + start_id = stop_id + update_arel = update_arel.where(table[:id].lt(stop_id)) + end + + update_arel = yield table, update_arel if block_given? + + execute(update_arel.to_sql) + end + + migrated += batch_size + if Time.now - last_time > 1 + status = "Migrated #{migrated} rows" + + percentage = 100.0 * migrated / total + status += " (~#{sprintf('%.2f', percentage)}%, " + + remaining_time = (100.0 - percentage) * (Time.now - started_time) / percentage + + status += "#{(remaining_time / 60).to_i}:" + status += sprintf('%02d', remaining_time.to_i % 60) + status += ' remaining, ' + + # Tell users not to interrupt if we're almost done. + if remaining_time > 10 + status += 'safe to interrupt' + else + status += 'DO NOT interrupt' + end + + status += ')' + + say status, true + last_time = Time.now + end + + # There are no more rows left to update. + break unless stop_row + end + end + + # Adds a column with a default value without locking an entire table. + # + # This method runs the following steps: + # + # 1. Add the column with a default value of NULL. + # 2. Change the default value of the column to the specified value. + # 3. Update all existing rows in batches. + # 4. Set a `NOT NULL` constraint on the column if desired (the default). + # + # These steps ensure a column can be added to a large and commonly used + # table without locking the entire table for the duration of the table + # modification. + # + # table - The name of the table to update. + # column - The name of the column to add. + # type - The column type (e.g. `:integer`). + # default - The default value for the column. + # limit - Sets a column limit. For example, for :integer, the default is + # 4-bytes. Set `limit: 8` to allow 8-byte integers. + # allow_null - When set to `true` the column will allow NULL values, the + # default is to not allow NULL values. + # + # This method can also take a block which is passed directly to the + # `update_column_in_batches` method. + def add_column_with_default(table, column, type, default:, limit: nil, allow_null: false, &block) + if transaction_open? + raise 'add_column_with_default can not be run inside a transaction, ' \ + 'you can disable transactions by calling disable_ddl_transaction! ' \ + 'in the body of your migration class' + end + + disable_statement_timeout + + transaction do + if limit + add_column(table, column, type, default: nil, limit: limit) + else + add_column(table, column, type, default: nil) + end + + # Changing the default before the update ensures any newly inserted + # rows already use the proper default value. + change_column_default(table, column, default) + end + + begin + update_column_in_batches(table, column, default, &block) + + change_column_null(table, column, false) unless allow_null + # We want to rescue _all_ exceptions here, even those that don't inherit + # from StandardError. + rescue Exception => error # rubocop: disable all + remove_column(table, column) + + raise error + end + end + + # Renames a column without requiring downtime. + # + # Concurrent renames work by using database triggers to ensure both the + # old and new column are in sync. However, this method will _not_ remove + # the triggers or the old column automatically; this needs to be done + # manually in a post-deployment migration. This can be done using the + # method `cleanup_concurrent_column_rename`. + # + # table - The name of the database table containing the column. + # old - The old column name. + # new - The new column name. + # type - The type of the new column. If no type is given the old column's + # type is used. + def rename_column_concurrently(table, old, new, type: nil) + if transaction_open? + raise 'rename_column_concurrently can not be run inside a transaction' + end + + check_trigger_permissions!(table) + trigger_name = rename_trigger_name(table, old, new) + + # If we were in the middle of update_column_in_batches, we should remove + # the old column and start over, as we have no idea where we were. + if column_for(table, new) + if MigrationHelpers.postgresql? + remove_rename_triggers_for_postgresql(table, trigger_name) + else + remove_rename_triggers_for_mysql(trigger_name) + end + + remove_column(table, new) + end + + old_col = column_for(table, old) + new_type = type || old_col.type + + col_opts = { + precision: old_col.precision, + scale: old_col.scale, + } + + # We may be trying to reset the limit on an integer column type, so let + # Rails handle that. + unless [:bigint, :integer].include?(new_type) + col_opts[:limit] = old_col.limit + end + + add_column(table, new, new_type, col_opts) + + # We set the default value _after_ adding the column so we don't end up + # updating any existing data with the default value. This isn't + # necessary since we copy over old values further down. + change_column_default(table, new, old_col.default) if old_col.default + + quoted_table = quote_table_name(table) + quoted_old = quote_column_name(old) + quoted_new = quote_column_name(new) + + if MigrationHelpers.postgresql? + install_rename_triggers_for_postgresql(trigger_name, quoted_table, + quoted_old, quoted_new) + else + install_rename_triggers_for_mysql(trigger_name, quoted_table, + quoted_old, quoted_new) + end + + update_column_in_batches(table, new, Arel::Table.new(table)[old]) + + change_column_null(table, new, false) unless old_col.null + + copy_indexes(table, old, new) + copy_foreign_keys(table, old, new) + end + + # Changes the type of a column concurrently. + # + # table - The table containing the column. + # column - The name of the column to change. + # new_type - The new column type. + def change_column_type_concurrently(table, column, new_type) + temp_column = rename_column_name(column) + + rename_column_concurrently(table, column, temp_column, type: new_type) + + # Primary keys don't necessarily have an associated index. + if ActiveRecord::Base.get_primary_key(table) == column.to_s + old_pk_index_name = "index_#{table}_on_#{column}" + new_pk_index_name = "index_#{table}_on_#{column}_cm" + + unless indexes_for(table, column).find{|i| i.name == old_pk_index_name} + add_concurrent_index(table, [temp_column], { + unique: true, + name: new_pk_index_name + }) + end + end + end + + # Performs cleanup of a concurrent type change. + # + # table - The table containing the column. + # column - The name of the column to change. + # new_type - The new column type. + def cleanup_concurrent_column_type_change(table, column) + temp_column = rename_column_name(column) + + # Wait for the indices to be built + indexes_for(table, column).each do |index| + expected_name = index.name + '_cm' + + puts "Waiting for index #{expected_name}" + sleep 1 until indexes_for(table, temp_column).find {|i| i.name == expected_name } + end + + was_primary = (ActiveRecord::Base.get_primary_key(table) == column.to_s) + old_default_fn = column_for(table, column).default_function + + old_fks = [] + if was_primary + # Get any foreign keys pointing at this column we need to recreate, and + # remove the old ones. + # Based on code from: + # http://errorbank.blogspot.com/2011/03/list-all-foreign-keys-references-for.html + old_fks_res = execute <<-EOF.strip_heredoc + select m.relname as src_table, + (select a.attname + from pg_attribute a + where a.attrelid = m.oid + and a.attnum = o.conkey[1] + and a.attisdropped = false) as src_col, + o.conname as name, + o.confdeltype as on_delete + from pg_constraint o + left join pg_class f on f.oid = o.confrelid + left join pg_class c on c.oid = o.conrelid + left join pg_class m on m.oid = o.conrelid + where o.contype = 'f' + and o.conrelid in ( + select oid from pg_class c where c.relkind = 'r') + and f.relname = '#{table}'; + EOF + old_fks = old_fks_res.to_a + old_fks.each do |old_fk| + add_concurrent_foreign_key( + old_fk['src_table'], + table, + column: old_fk['src_col'], + target_col: temp_column, + on_delete: extract_foreign_key_action(old_fk['on_delete']) + ) + + remove_foreign_key(old_fk['src_table'], name: old_fk['name']) + end + end + + # If there was a sequence owned by the old column, make it owned by the + # new column, as it will otherwise be deleted when we get rid of the + # old column. + if (seq_match = /^nextval\('([^']*)'(::text|::regclass)?\)/.match(old_default_fn)) + seq_name = seq_match[1] + execute("ALTER SEQUENCE #{seq_name} OWNED BY #{table}.#{temp_column}") + end + + transaction do + # This has to be performed in a transaction as otherwise we might have + # inconsistent data. + + cleanup_concurrent_column_rename(table, column, temp_column) + rename_column(table, temp_column, column) + + # If there was an old default function, we didn't copy it. Do that now + # in the transaction, so we don't miss anything. + change_column_default(table, column, -> { old_default_fn }) if old_default_fn + end + + # Rename any indices back to what they should be. + indexes_for(table, column).each do |index| + next unless index.name.end_with?('_cm') + + real_index_name = index.name.sub(/_cm$/, '') + rename_index(table, index.name, real_index_name) + end + + # Rename any foreign keys back to names based on the real column. + foreign_keys_for(table, column).each do |fk| + old_fk_name = concurrent_foreign_key_name(fk.from_table, temp_column, 'id') + new_fk_name = concurrent_foreign_key_name(fk.from_table, column, 'id') + execute("ALTER TABLE #{fk.from_table} RENAME CONSTRAINT " + + "#{old_fk_name} TO #{new_fk_name}") + end + + # Rename any foreign keys from other tables to names based on the real + # column. + old_fks.each do |old_fk| + old_fk_name = concurrent_foreign_key_name(old_fk['src_table'], + old_fk['src_col'], temp_column) + new_fk_name = concurrent_foreign_key_name(old_fk['src_table'], + old_fk['src_col'], column) + execute("ALTER TABLE #{old_fk['src_table']} RENAME CONSTRAINT " + + "#{old_fk_name} TO #{new_fk_name}") + end + + # If the old column was a primary key, mark the new one as a primary key. + if was_primary + execute("ALTER TABLE #{table} ADD PRIMARY KEY USING INDEX " + + "index_#{table}_on_#{column}") + end + end + + # Cleans up a concurrent column name. + # + # This method takes care of removing previously installed triggers as well + # as removing the old column. + # + # table - The name of the database table. + # old - The name of the old column. + # new - The name of the new column. + def cleanup_concurrent_column_rename(table, old, new) + trigger_name = rename_trigger_name(table, old, new) + + check_trigger_permissions!(table) + + if MigrationHelpers.postgresql? + remove_rename_triggers_for_postgresql(table, trigger_name) + else + remove_rename_triggers_for_mysql(trigger_name) + end + + remove_column(table, old) + end + + # Performs a concurrent column rename when using PostgreSQL. + def install_rename_triggers_for_postgresql(trigger, table, old, new) + execute <<-EOF.strip_heredoc + CREATE OR REPLACE FUNCTION #{trigger}() + RETURNS trigger AS + $BODY$ + BEGIN + NEW.#{new} := NEW.#{old}; + RETURN NEW; + END; + $BODY$ + LANGUAGE 'plpgsql' + VOLATILE + EOF + + execute <<-EOF.strip_heredoc + CREATE TRIGGER #{trigger} + BEFORE INSERT OR UPDATE + ON #{table} + FOR EACH ROW + EXECUTE PROCEDURE #{trigger}() + EOF + end + + # Installs the triggers necessary to perform a concurrent column rename on + # MySQL. + def install_rename_triggers_for_mysql(trigger, table, old, new) + execute <<-EOF.strip_heredoc + CREATE TRIGGER #{trigger}_insert + BEFORE INSERT + ON #{table} + FOR EACH ROW + SET NEW.#{new} = NEW.#{old} + EOF + + execute <<-EOF.strip_heredoc + CREATE TRIGGER #{trigger}_update + BEFORE UPDATE + ON #{table} + FOR EACH ROW + SET NEW.#{new} = NEW.#{old} + EOF + end + + # Removes the triggers used for renaming a PostgreSQL column concurrently. + def remove_rename_triggers_for_postgresql(table, trigger) + execute("DROP TRIGGER IF EXISTS #{trigger} ON #{table}") + execute("DROP FUNCTION IF EXISTS #{trigger}()") + end + + # Removes the triggers used for renaming a MySQL column concurrently. + def remove_rename_triggers_for_mysql(trigger) + execute("DROP TRIGGER IF EXISTS #{trigger}_insert") + execute("DROP TRIGGER IF EXISTS #{trigger}_update") + end + + # Returns the (base) name to use for triggers when renaming columns. + def rename_trigger_name(table, old, new) + 'trigger_' + Digest::SHA256.hexdigest("#{table}_#{old}_#{new}").first(12) + end + + # Returns the name to use for temporary rename columns. + def rename_column_name(base) + base.to_s + '_cm' + end + + # Returns an Array containing the indexes for the given column + def indexes_for(table, column) + column = column.to_s + + indexes(table).select { |index| index.columns.include?(column) } + end + + # Returns an Array containing the foreign keys for the given column. + def foreign_keys_for(table, column) + column = column.to_s + + foreign_keys(table).select { |fk| fk.column == column } + end + + # Copies all indexes for the old column to a new column. + # + # table - The table containing the columns and indexes. + # old - The old column. + # new - The new column. + def copy_indexes(table, old, new) + old = old.to_s + new = new.to_s + + indexes_for(table, old).each do |index| + new_columns = index.columns.map do |column| + column == old ? new : column + end + + # This is necessary as we can't properly rename indexes such as + # "ci_taggings_idx". + name = index.name + '_cm' + + # If the order contained the old column, map it to the new one. + order = index.orders + if order.key?(old) + order[new] = order.delete(old) + end + + options = { + unique: index.unique, + name: name, + length: index.lengths, + order: order + } + + # These options are not supported by MySQL, so we only add them if + # they were previously set. + options[:using] = index.using if index.using + options[:where] = index.where if index.where + + add_concurrent_index(table, new_columns, options) + end + end + + # Copies all foreign keys for the old column to the new column. + # + # table - The table containing the columns and indexes. + # old - The old column. + # new - The new column. + def copy_foreign_keys(table, old, new) + foreign_keys_for(table, old).each do |fk| + add_concurrent_foreign_key(fk.from_table, + fk.to_table, + column: new, + on_delete: fk.on_delete) + end + end + + # Returns the column for the given table and column name. + def column_for(table, name) + name = name.to_s + + columns(table).find { |column| column.name == name } + end + + # This will replace the first occurance of a string in a column with + # the replacement + # On postgresql we can use `regexp_replace` for that. + # On mysql we find the location of the pattern, and overwrite it + # with the replacement + def replace_sql(column, pattern, replacement) + quoted_pattern = Arel::Nodes::Quoted.new(pattern.to_s) + quoted_replacement = Arel::Nodes::Quoted.new(replacement.to_s) + + if MigrationHelpers.mysql? + locate = Arel::Nodes::NamedFunction + .new('locate', [quoted_pattern, column]) + insert_in_place = Arel::Nodes::NamedFunction + .new('insert', [column, locate, pattern.size, quoted_replacement]) + + Arel::Nodes::SqlLiteral.new(insert_in_place.to_sql) + else + replace = Arel::Nodes::NamedFunction + .new("regexp_replace", [column, quoted_pattern, quoted_replacement]) + Arel::Nodes::SqlLiteral.new(replace.to_sql) + end + end + + def remove_foreign_key_without_error(*args) + remove_foreign_key(*args) + rescue ArgumentError + end + + def sidekiq_queue_migrate(queue_from, to:) + while sidekiq_queue_length(queue_from) > 0 + Sidekiq.redis do |conn| + conn.rpoplpush "queue:#{queue_from}", "queue:#{to}" + end + end + end + + def sidekiq_queue_length(queue_name) + Sidekiq.redis do |conn| + conn.llen("queue:#{queue_name}") + end + end + + def check_trigger_permissions!(table) + unless Grant.create_and_execute_trigger?(table) + dbname = ActiveRecord::Base.configurations[Rails.env]['database'] + user = ActiveRecord::Base.configurations[Rails.env]['username'] || ENV['USER'] + + raise <<-EOF +Your database user is not allowed to create, drop, or execute triggers on the +table #{table}. + +If you are using PostgreSQL you can solve this by logging in to the GitLab +database (#{dbname}) using a super user and running: + + ALTER #{user} WITH SUPERUSER + +For MySQL you instead need to run: + + GRANT ALL PRIVILEGES ON *.* TO #{user}@'%' + +Both queries will grant the user super user permissions, ensuring you don't run +into similar problems in the future (e.g. when new tables are created). + EOF + end + end + + # Bulk queues background migration jobs for an entire table, batched by ID range. + # "Bulk" meaning many jobs will be pushed at a time for efficiency. + # If you need a delay interval per job, then use `queue_background_migration_jobs_by_range_at_intervals`. + # + # model_class - The table being iterated over + # job_class_name - The background migration job class as a string + # batch_size - The maximum number of rows per job + # + # Example: + # + # class Route < ActiveRecord::Base + # include EachBatch + # self.table_name = 'routes' + # end + # + # bulk_queue_background_migration_jobs_by_range(Route, 'ProcessRoutes') + # + # Where the model_class includes EachBatch, and the background migration exists: + # + # class Gitlab::BackgroundMigration::ProcessRoutes + # def perform(start_id, end_id) + # # do something + # end + # end + def bulk_queue_background_migration_jobs_by_range(model_class, job_class_name, batch_size: BACKGROUND_MIGRATION_BATCH_SIZE) + raise "#{model_class} does not have an ID to use for batch ranges" unless model_class.column_names.include?('id') + + jobs = [] + + model_class.each_batch(of: batch_size) do |relation| + start_id, end_id = relation.pluck('MIN(id), MAX(id)').first + + if jobs.length >= BACKGROUND_MIGRATION_JOB_BUFFER_SIZE + # Note: This code path generally only helps with many millions of rows + # We push multiple jobs at a time to reduce the time spent in + # Sidekiq/Redis operations. We're using this buffer based approach so we + # don't need to run additional queries for every range. + BackgroundMigrationWorker.perform_bulk(jobs) + jobs.clear + end + + jobs << [job_class_name, [start_id, end_id]] + end + + BackgroundMigrationWorker.perform_bulk(jobs) unless jobs.empty? + end + + # Queues background migration jobs for an entire table, batched by ID range. + # Each job is scheduled with a `delay_interval` in between. + # If you use a small interval, then some jobs may run at the same time. + # + # model_class - The table being iterated over + # job_class_name - The background migration job class as a string + # delay_interval - The duration between each job's scheduled time (must respond to `to_f`) + # batch_size - The maximum number of rows per job + # + # Example: + # + # class Route < ActiveRecord::Base + # include EachBatch + # self.table_name = 'routes' + # end + # + # queue_background_migration_jobs_by_range_at_intervals(Route, 'ProcessRoutes', 1.minute) + # + # Where the model_class includes EachBatch, and the background migration exists: + # + # class Gitlab::BackgroundMigration::ProcessRoutes + # def perform(start_id, end_id) + # # do something + # end + # end + def queue_background_migration_jobs_by_range_at_intervals(model_class, job_class_name, delay_interval, batch_size: BACKGROUND_MIGRATION_BATCH_SIZE) + raise "#{model_class} does not have an ID to use for batch ranges" unless model_class.column_names.include?('id') + + model_class.each_batch(of: batch_size) do |relation, index| + start_id, end_id = relation.pluck('MIN(id), MAX(id)').first + + # `BackgroundMigrationWorker.bulk_perform_in` schedules all jobs for + # the same time, which is not helpful in most cases where we wish to + # spread the work over time. + BackgroundMigrationWorker.perform_in(delay_interval * index, job_class_name, [start_id, end_id]) + end + end + end +end + +# rubocop:enable all -- cgit From 468523f4ad85f99d78fd341ca4f5fc96f561a533 Mon Sep 17 00:00:00 2001 From: aschmitz Date: Wed, 4 Oct 2017 02:56:37 -0500 Subject: Non-Serial ("Snowflake") IDs (#4801) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future. --- .../api/v1/accounts/relationships_controller.rb | 5 +- app/lib/feed_manager.rb | 128 +++++++++++++++++---- app/models/feed.rb | 2 +- app/services/batched_remove_status_service.rb | 37 ++---- app/services/precompute_feed_service.rb | 38 +----- app/services/remove_status_service.rb | 8 +- .../20170920024819_status_ids_to_timestamp_ids.rb | 32 ++++++ db/migrate/20170920032311_fix_reblogs_in_feeds.rb | 63 ++++++++++ db/schema.rb | 2 +- lib/mastodon/timestamp_ids.rb | 126 ++++++++++++++++++++ lib/tasks/db.rake | 56 +++++++++ spec/lib/feed_manager_spec.rb | 109 ++++++++++++++++++ spec/models/feed_spec.rb | 2 +- .../services/batched_remove_status_service_spec.rb | 3 +- spec/services/precompute_feed_service_spec.rb | 2 +- 15 files changed, 509 insertions(+), 104 deletions(-) create mode 100644 db/migrate/20170920024819_status_ids_to_timestamp_ids.rb create mode 100644 db/migrate/20170920032311_fix_reblogs_in_feeds.rb create mode 100644 lib/mastodon/timestamp_ids.rb (limited to 'db') diff --git a/app/controllers/api/v1/accounts/relationships_controller.rb b/app/controllers/api/v1/accounts/relationships_controller.rb index a88cf2021..91a942d75 100644 --- a/app/controllers/api/v1/accounts/relationships_controller.rb +++ b/app/controllers/api/v1/accounts/relationships_controller.rb @@ -7,7 +7,10 @@ class Api::V1::Accounts::RelationshipsController < Api::BaseController respond_to :json def index - @accounts = Account.where(id: account_ids).select('id') + accounts = Account.where(id: account_ids).select('id') + # .where doesn't guarantee that our results are in the same order + # we requested them, so return the "right" order to the requestor. + @accounts = accounts.index_by(&:id).values_at(*account_ids) render json: @accounts, each_serializer: REST::RelationshipSerializer, relationships: relationships end diff --git a/app/lib/feed_manager.rb b/app/lib/feed_manager.rb index b1ae11084..c509c5702 100644 --- a/app/lib/feed_manager.rb +++ b/app/lib/feed_manager.rb @@ -7,8 +7,13 @@ class FeedManager MAX_ITEMS = 400 - def key(type, id) - "feed:#{type}:#{id}" + # Must be <= MAX_ITEMS or the tracking sets will grow forever + REBLOG_FALLOFF = 40 + + def key(type, id, subtype = nil) + return "feed:#{type}:#{id}" unless subtype + + "feed:#{type}:#{id}:#{subtype}" end def filter?(timeline_type, status, receiver_id) @@ -22,23 +27,36 @@ class FeedManager end def push(timeline_type, account, status) - timeline_key = key(timeline_type, account.id) + return false unless add_to_feed(timeline_type, account, status) - if status.reblog? - # If the original status is within 40 statuses from top, do not re-insert it into the feed - rank = redis.zrevrank(timeline_key, status.reblog_of_id) - return if !rank.nil? && rank < 40 - redis.zadd(timeline_key, status.id, status.reblog_of_id) - else - redis.zadd(timeline_key, status.id, status.id) - trim(timeline_type, account.id) - end + trim(timeline_type, account.id) PushUpdateWorker.perform_async(account.id, status.id) if push_update_required?(timeline_type, account.id) + + true + end + + def unpush(timeline_type, account, status) + return false unless remove_from_feed(timeline_type, account, status) + + payload = Oj.dump(event: :delete, payload: status.id.to_s) + Redis.current.publish("timeline:#{account.id}", payload) + + true end def trim(type, account_id) - redis.zremrangebyrank(key(type, account_id), '0', (-(FeedManager::MAX_ITEMS + 1)).to_s) + timeline_key = key(type, account_id) + reblog_key = key(type, account_id, 'reblogs') + # Remove any items past the MAX_ITEMS'th entry in our feed + redis.zremrangebyrank(timeline_key, '0', (-(FeedManager::MAX_ITEMS + 1)).to_s) + + # Get the score of the REBLOG_FALLOFF'th item in our feed, and stop + # tracking anything after it for deduplication purposes. + falloff_rank = FeedManager::REBLOG_FALLOFF - 1 + falloff_range = redis.zrevrange(timeline_key, falloff_rank, falloff_rank, with_scores: true) + falloff_score = falloff_range&.first&.last&.to_i || 0 + redis.zremrangebyscore(reblog_key, 0, falloff_score) end def push_update_required?(timeline_type, account_id) @@ -54,11 +72,9 @@ class FeedManager query = query.where('id > ?', oldest_home_score) end - redis.pipelined do - query.each do |status| - next if status.direct_visibility? || filter?(:home, status, into_account) - redis.zadd(timeline_key, status.id, status.id) - end + query.each do |status| + next if status.direct_visibility? || filter?(:home, status, into_account) + add_to_feed(:home, into_account, status) end trim(:home, into_account.id) @@ -69,11 +85,8 @@ class FeedManager oldest_home_score = redis.zrange(timeline_key, 0, 0, with_scores: true)&.first&.last&.to_i || 0 from_account.statuses.select('id').where('id > ?', oldest_home_score).reorder(nil).find_in_batches do |statuses| - redis.pipelined do - statuses.each do |status| - redis.zrem(timeline_key, status.id) - redis.zremrangebyscore(timeline_key, status.id, status.id) - end + statuses.each do |status| + unpush(:home, into_account, status) end end end @@ -81,9 +94,20 @@ class FeedManager def clear_from_timeline(account, target_account) timeline_key = key(:home, account.id) timeline_status_ids = redis.zrange(timeline_key, 0, -1) - target_status_ids = Status.where(id: timeline_status_ids, account: target_account).ids + target_statuses = Status.where(id: timeline_status_ids, account: target_account) - redis.zrem(timeline_key, target_status_ids) if target_status_ids.present? + target_statuses.each do |status| + unpush(:home, account, status) + end + end + + def populate_feed(account) + prepopulate_limit = FeedManager::MAX_ITEMS / 4 + statuses = Status.as_home_timeline(account).order(account_id: :desc).limit(prepopulate_limit) + statuses.reverse_each do |status| + next if filter_from_home?(status, account) + add_to_feed(:home, account, status) + end end private @@ -131,4 +155,58 @@ class FeedManager should_filter end + + # Adds a status to an account's feed, returning true if a status was + # added, and false if it was not added to the feed. Note that this is + # an internal helper: callers must call trim or push updates if + # either action is appropriate. + def add_to_feed(timeline_type, account, status) + timeline_key = key(timeline_type, account.id) + reblog_key = key(timeline_type, account.id, 'reblogs') + + if status.reblog? + # If the original status or a reblog of it is within + # REBLOG_FALLOFF statuses from the top, do not re-insert it into + # the feed + rank = redis.zrevrank(timeline_key, status.reblog_of_id) + return false if !rank.nil? && rank < FeedManager::REBLOG_FALLOFF + + reblog_rank = redis.zrevrank(reblog_key, status.reblog_of_id) + return false unless reblog_rank.nil? + + redis.zadd(timeline_key, status.id, status.id) + redis.zadd(reblog_key, status.id, status.reblog_of_id) + else + redis.zadd(timeline_key, status.id, status.id) + end + + true + end + + # Removes an individual status from a feed, correctly handling cases + # with reblogs, and returning true if a status was removed. As with + # `add_to_feed`, this does not trigger push updates, so callers must + # do so if appropriate. + def remove_from_feed(timeline_type, account, status) + timeline_key = key(timeline_type, account.id) + reblog_key = key(timeline_type, account.id, 'reblogs') + + if status.reblog? + # 1. If the reblogging status is not in the feed, stop. + status_rank = redis.zrevrank(timeline_key, status.id) + return false if status_rank.nil? + + # 2. Remove the reblogged status from the `:reblogs` zset. + redis.zrem(reblog_key, status.reblog_of_id) + + # 3. Add the reblogged status to the feed using the reblogging + # status' ID as its score, and the reblogged status' ID as its + # value. + redis.zadd(timeline_key, status.id, status.reblog_of_id) + + # 4. Remove the reblogging status from the feed (as normal) + end + + redis.zrem(timeline_key, status.id) + end end diff --git a/app/models/feed.rb b/app/models/feed.rb index beb4a8de3..5f7b7877a 100644 --- a/app/models/feed.rb +++ b/app/models/feed.rb @@ -19,7 +19,7 @@ class Feed def from_redis(limit, max_id, since_id) max_id = '+inf' if max_id.blank? since_id = '-inf' if since_id.blank? - unhydrated = redis.zrevrangebyscore(key, "(#{max_id}", "(#{since_id}", limit: [0, limit], with_scores: true).map(&:last).map(&:to_i) + unhydrated = redis.zrevrangebyscore(key, "(#{max_id}", "(#{since_id}", limit: [0, limit], with_scores: true).map(&:first).map(&:to_i) Status.where(id: unhydrated).cache_ids end diff --git a/app/services/batched_remove_status_service.rb b/app/services/batched_remove_status_service.rb index 2fd623922..5d83771c9 100644 --- a/app/services/batched_remove_status_service.rb +++ b/app/services/batched_remove_status_service.rb @@ -29,7 +29,7 @@ class BatchedRemoveStatusService < BaseService statuses.group_by(&:account_id).each do |_, account_statuses| account = account_statuses.first.account - unpush_from_home_timelines(account_statuses) + unpush_from_home_timelines(account, account_statuses) if account.local? batch_stream_entries(account, account_statuses) @@ -72,14 +72,15 @@ class BatchedRemoveStatusService < BaseService end end - def unpush_from_home_timelines(statuses) - account = statuses.first.account - recipients = account.followers.local.pluck(:id) + def unpush_from_home_timelines(account, statuses) + recipients = account.followers.local.to_a - recipients << account.id if account.local? + recipients << account if account.local? - recipients.each do |follower_id| - unpush(follower_id, statuses) + recipients.each do |follower| + statuses.each do |status| + FeedManager.instance.unpush(:home, follower, status) + end end end @@ -109,28 +110,6 @@ class BatchedRemoveStatusService < BaseService end end - def unpush(follower_id, statuses) - key = FeedManager.instance.key(:home, follower_id) - - originals = statuses.reject(&:reblog?) - reblogs = statuses.select(&:reblog?) - - # Quickly remove all originals - redis.pipelined do - originals.each do |status| - redis.zremrangebyscore(key, status.id, status.id) - redis.publish("timeline:#{follower_id}", @json_payloads[status.id]) - end - end - - # For reblogs, re-add original status to feed, unless the reblog - # was not in the feed in the first place - reblogs.each do |status| - redis.zadd(key, status.reblog_of_id, status.reblog_of_id) unless redis.zscore(key, status.reblog_of_id).nil? - redis.publish("timeline:#{follower_id}", @json_payloads[status.id]) - end - end - def redis Redis.current end diff --git a/app/services/precompute_feed_service.rb b/app/services/precompute_feed_service.rb index 85635a008..36aabaa00 100644 --- a/app/services/precompute_feed_service.rb +++ b/app/services/precompute_feed_service.rb @@ -1,43 +1,7 @@ # frozen_string_literal: true class PrecomputeFeedService < BaseService - LIMIT = FeedManager::MAX_ITEMS / 4 - def call(account) - @account = account - populate_feed - end - - private - - attr_reader :account - - def populate_feed - pairs = statuses.reverse_each.lazy.reject(&method(:status_filtered?)).map(&method(:process_status)).to_a - - redis.pipelined do - redis.zadd(account_home_key, pairs) if pairs.any? - redis.del("account:#{@account.id}:regeneration") - end - end - - def process_status(status) - [status.id, status.reblog? ? status.reblog_of_id : status.id] - end - - def status_filtered?(status) - FeedManager.instance.filter?(:home, status, account.id) - end - - def account_home_key - FeedManager.instance.key(:home, account.id) - end - - def statuses - Status.as_home_timeline(account).order(account_id: :desc).limit(LIMIT) - end - - def redis - Redis.current + FeedManager.instance.populate_feed(account) end end diff --git a/app/services/remove_status_service.rb b/app/services/remove_status_service.rb index 14f24908c..96d9208cc 100644 --- a/app/services/remove_status_service.rb +++ b/app/services/remove_status_service.rb @@ -102,13 +102,7 @@ class RemoveStatusService < BaseService end def unpush(type, receiver, status) - if status.reblog? && !redis.zscore(FeedManager.instance.key(type, receiver.id), status.reblog_of_id).nil? - redis.zadd(FeedManager.instance.key(type, receiver.id), status.reblog_of_id, status.reblog_of_id) - else - redis.zremrangebyscore(FeedManager.instance.key(type, receiver.id), status.id, status.id) - end - - Redis.current.publish("timeline:#{receiver.id}", @payload) + FeedManager.instance.unpush(type, receiver, status) end def remove_from_hashtags diff --git a/db/migrate/20170920024819_status_ids_to_timestamp_ids.rb b/db/migrate/20170920024819_status_ids_to_timestamp_ids.rb new file mode 100644 index 000000000..5d15817bd --- /dev/null +++ b/db/migrate/20170920024819_status_ids_to_timestamp_ids.rb @@ -0,0 +1,32 @@ +class StatusIdsToTimestampIds < ActiveRecord::Migration[5.1] + def up + # Prepare the function we will use to generate IDs. + Rake::Task['db:define_timestamp_id'].execute + + # Set up the statuses.id column to use our timestamp-based IDs. + ActiveRecord::Base.connection.execute(<<~SQL) + ALTER TABLE statuses + ALTER COLUMN id + SET DEFAULT timestamp_id('statuses') + SQL + + # Make sure we have a sequence to use. + Rake::Task['db:ensure_id_sequences_exist'].execute + end + + def down + # Revert the column to the old method of just using the sequence + # value for new IDs. Set the current ID sequence to the maximum + # existing ID, such that the next sequence will be one higher. + + # We lock the table during this so that the ID won't get clobbered, + # but ID is indexed, so this should be a fast operation. + ActiveRecord::Base.connection.execute(<<~SQL) + LOCK statuses; + SELECT setval('statuses_id_seq', (SELECT MAX(id) FROM statuses)); + ALTER TABLE statuses + ALTER COLUMN id + SET DEFAULT nextval('statuses_id_seq');" + SQL + end +end diff --git a/db/migrate/20170920032311_fix_reblogs_in_feeds.rb b/db/migrate/20170920032311_fix_reblogs_in_feeds.rb new file mode 100644 index 000000000..c813ecd46 --- /dev/null +++ b/db/migrate/20170920032311_fix_reblogs_in_feeds.rb @@ -0,0 +1,63 @@ +class FixReblogsInFeeds < ActiveRecord::Migration[5.1] + def up + redis = Redis.current + fm = FeedManager.instance + + # find_each is batched on the database side. + User.includes(:account).find_each do |user| + account = user.account + + # Old scheme: + # Each user's feed zset had a series of score:value entries, + # where "regular" statuses had the same score and value (their + # ID). Reblogs had a score of the reblogging status' ID, and a + # value of the reblogged status' ID. + + # New scheme: + # The feed contains only entries with the same score and value. + # Reblogs result in the reblogging status being added to the + # feed, with an entry in a reblog tracking zset (where the score + # is once again set to the reblogging status' ID, and the value + # is set to the reblogged status' ID). This is safe for Redis' + # float coersion because in this reblog tracking zset, we only + # need the rebloggging status' ID to be able to stop tracking + # entries after they have gotten too far down the feed, which + # does not require an exact value. + + # So, first, we iterate over the user's feed to find any reblogs. + timeline_key = fm.key(:home, account.id) + reblog_key = fm.key(:home, account.id, 'reblogs') + redis.zrange(timeline_key, 0, -1, with_scores: true).each do |entry| + next if entry[0] == entry[1] + + # The score and value don't match, so this is a reblog. + # (note that we're transitioning from IDs < 53 bits so we + # don't have to worry about the loss of precision) + + reblogged_id, reblogging_id = entry + + # Remove the old entry + redis.zrem(timeline_key, reblogged_id) + + # Add a new one for the reblogging status + redis.zadd(timeline_key, reblogging_id, reblogging_id) + + # Track the fact that this was a reblog + redis.zadd(reblog_key, reblogging_id, reblogged_id) + end + end + end + + def down + # We *deliberately* do nothing here. This means that reverting + # this and the associated changes to the FeedManager code could + # allow one superfluous reblog of any given status, but in the case + # where things have gone wrong and a revert is necessary, this + # appears preferable to requiring a database hit for every status + # in every users' feed simply to revert. + + # Note that this is operating under the assumption that entries + # with >53-bit IDs have already been entered. Otherwise, we could + # just use the data in Redis to reverse this transition. + end +end diff --git a/db/schema.rb b/db/schema.rb index 2cb105553..00cc24bae 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -321,7 +321,7 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.index ["account_id", "status_id"], name: "index_status_pins_on_account_id_and_status_id", unique: true end - create_table "statuses", force: :cascade do |t| + create_table "statuses", id: :bigint, default: -> { "timestamp_id('statuses'::text)" }, force: :cascade do |t| t.string "uri" t.text "text", default: "", null: false t.datetime "created_at", null: false diff --git a/lib/mastodon/timestamp_ids.rb b/lib/mastodon/timestamp_ids.rb new file mode 100644 index 000000000..d49b5c1b5 --- /dev/null +++ b/lib/mastodon/timestamp_ids.rb @@ -0,0 +1,126 @@ +# frozen_string_literal: true + +module Mastodon + module TimestampIds + def self.define_timestamp_id + conn = ActiveRecord::Base.connection + + # Make sure we don't already have a `timestamp_id` function. + unless conn.execute(<<~SQL).values.first.first + SELECT EXISTS( + SELECT * FROM pg_proc WHERE proname = 'timestamp_id' + ); + SQL + # The function doesn't exist, so we'll define it. + conn.execute(<<~SQL) + CREATE OR REPLACE FUNCTION timestamp_id(table_name text) + RETURNS bigint AS + $$ + DECLARE + time_part bigint; + sequence_base bigint; + tail bigint; + BEGIN + -- Our ID will be composed of the following: + -- 6 bytes (48 bits) of millisecond-level timestamp + -- 2 bytes (16 bits) of sequence data + + -- The 'sequence data' is intended to be unique within a + -- given millisecond, yet obscure the 'serial number' of + -- this row. + + -- To do this, we hash the following data: + -- * Table name (if provided, skipped if not) + -- * Secret salt (should not be guessable) + -- * Timestamp (again, millisecond-level granularity) + + -- We then take the first two bytes of that value, and add + -- the lowest two bytes of the table ID sequence number + -- (`table_name`_id_seq). This means that even if we insert + -- two rows at the same millisecond, they will have + -- distinct 'sequence data' portions. + + -- If this happens, and an attacker can see both such IDs, + -- they can determine which of the two entries was inserted + -- first, but not the total number of entries in the table + -- (even mod 2**16). + + -- The table name is included in the hash to ensure that + -- different tables derive separate sequence bases so rows + -- inserted in the same millisecond in different tables do + -- not reveal the table ID sequence number for one another. + + -- The secret salt is included in the hash to ensure that + -- external users cannot derive the sequence base given the + -- timestamp and table name, which would allow them to + -- compute the table ID sequence number. + + time_part := ( + -- Get the time in milliseconds + ((date_part('epoch', now()) * 1000))::bigint + -- And shift it over two bytes + << 16); + + sequence_base := ( + 'x' || + -- Take the first two bytes (four hex characters) + substr( + -- Of the MD5 hash of the data we documented + md5(table_name || + '#{SecureRandom.hex(16)}' || + time_part::text + ), + 1, 4 + ) + -- And turn it into a bigint + )::bit(16)::bigint; + + -- Finally, add our sequence number to our base, and chop + -- it to the last two bytes + tail := ( + (sequence_base + nextval(table_name || '_id_seq')) + & 65535); + + -- Return the time part and the sequence part. OR appears + -- faster here than addition, but they're equivalent: + -- time_part has no trailing two bytes, and tail is only + -- the last two bytes. + RETURN time_part | tail; + END + $$ LANGUAGE plpgsql VOLATILE; + SQL + end + end + + def self.ensure_id_sequences_exist + conn = ActiveRecord::Base.connection + + # Find tables using timestamp IDs. + default_regex = /timestamp_id\('(?\w+)'/ + conn.tables.each do |table| + # We're only concerned with "id" columns. + next unless (id_col = conn.columns(table).find { |col| col.name == 'id' }) + + # And only those that are using timestamp_id. + next unless (data = default_regex.match(id_col.default_function)) + + seq_name = data[:seq_prefix] + '_id_seq' + # If we were on Postgres 9.5+, we could do CREATE SEQUENCE IF + # NOT EXISTS, but we can't depend on that. Instead, catch the + # possible exception and ignore it. + # Note that seq_name isn't a column name, but it's a + # relation, like a column, and follows the same quoting rules + # in Postgres. + conn.execute(<<~SQL) + DO $$ + BEGIN + CREATE SEQUENCE #{conn.quote_column_name(seq_name)}; + EXCEPTION WHEN duplicate_table THEN + -- Do nothing, we have the sequence already. + END + $$ LANGUAGE plpgsql; + SQL + end + end + end +end diff --git a/lib/tasks/db.rake b/lib/tasks/db.rake index 7a055bf25..66468d999 100644 --- a/lib/tasks/db.rake +++ b/lib/tasks/db.rake @@ -1,5 +1,36 @@ # frozen_string_literal: true +require Rails.root.join('lib', 'mastodon', 'timestamp_ids') + +def each_schema_load_environment + # If we're in development, also run this for the test environment. + # This is a somewhat hacky way to do this, so here's why: + # 1. We have to define this before we load the schema, or we won't + # have a timestamp_id function when we get to it in the schema. + # 2. db:setup calls db:schema:load_if_ruby, which calls + # db:schema:load, which we define above as having a prerequisite + # of this task. + # 3. db:schema:load ends up running + # ActiveRecord::Tasks::DatabaseTasks.load_schema_current, which + # calls a private method `each_current_configuration`, which + # explicitly also does the loading for the `test` environment + # if the current environment is `development`, so we end up + # needing to do the same, and we can't even use the same method + # to do it. + + if Rails.env == 'development' + test_conf = ActiveRecord::Base.configurations['test'] + if test_conf['database']&.present? + ActiveRecord::Base.establish_connection(:test) + yield + + ActiveRecord::Base.establish_connection(Rails.env.to_sym) + end + end + + yield +end + namespace :db do namespace :migrate do desc 'Setup the db or migrate depending on state of db' @@ -16,4 +47,29 @@ namespace :db do end end end + + # Before we load the schema, define the timestamp_id function. + # Idiomatically, we might do this in a migration, but then it + # wouldn't end up in schema.rb, so we'd need to figure out a way to + # get it in before doing db:setup as well. This is simpler, and + # ensures it's always in place. + Rake::Task['db:schema:load'].enhance ['db:define_timestamp_id'] + + # After we load the schema, make sure we have sequences for each + # table using timestamp IDs. + Rake::Task['db:schema:load'].enhance do + Rake::Task['db:ensure_id_sequences_exist'].invoke + end + + task :define_timestamp_id do + each_schema_load_environment do + Mastodon::TimestampIds.define_timestamp_id + end + end + + task :ensure_id_sequences_exist do + each_schema_load_environment do + Mastodon::TimestampIds.ensure_id_sequences_exist + end + end end diff --git a/spec/lib/feed_manager_spec.rb b/spec/lib/feed_manager_spec.rb index 22439cf35..923894ccb 100644 --- a/spec/lib/feed_manager_spec.rb +++ b/spec/lib/feed_manager_spec.rb @@ -1,6 +1,10 @@ require 'rails_helper' RSpec.describe FeedManager do + it 'tracks at least as many statuses as reblogs' do + expect(FeedManager::REBLOG_FALLOFF).to be <= FeedManager::MAX_ITEMS + end + describe '#key' do subject { FeedManager.instance.key(:home, 1) } @@ -150,5 +154,110 @@ RSpec.describe FeedManager do expect(Redis.current.zcard("feed:type:#{account.id}")).to eq FeedManager::MAX_ITEMS end + + it 'sends push updates for non-home timelines' do + account = Fabricate(:account) + status = Fabricate(:status) + allow(Redis.current).to receive_messages(publish: nil) + + FeedManager.instance.push('type', account, status) + + expect(Redis.current).to have_received(:publish).with("timeline:#{account.id}", any_args).at_least(:once) + end + + context 'reblogs' do + it 'saves reblogs of unseen statuses' do + account = Fabricate(:account) + reblogged = Fabricate(:status) + reblog = Fabricate(:status, reblog: reblogged) + + expect(FeedManager.instance.push('type', account, reblog)).to be true + end + + it 'does not save a new reblog of a recent status' do + account = Fabricate(:account) + reblogged = Fabricate(:status) + reblog = Fabricate(:status, reblog: reblogged) + + FeedManager.instance.push('type', account, reblogged) + + expect(FeedManager.instance.push('type', account, reblog)).to be false + end + + it 'saves a new reblog of an old status' do + account = Fabricate(:account) + reblogged = Fabricate(:status) + reblog = Fabricate(:status, reblog: reblogged) + + FeedManager.instance.push('type', account, reblogged) + + # Fill the feed with intervening statuses + FeedManager::REBLOG_FALLOFF.times do + FeedManager.instance.push('type', account, Fabricate(:status)) + end + + expect(FeedManager.instance.push('type', account, reblog)).to be true + end + + it 'does not save a new reblog of a recently-reblogged status' do + account = Fabricate(:account) + reblogged = Fabricate(:status) + reblogs = 2.times.map { Fabricate(:status, reblog: reblogged) } + + # The first reblog will be accepted + FeedManager.instance.push('type', account, reblogs.first) + + # The second reblog should be ignored + expect(FeedManager.instance.push('type', account, reblogs.last)).to be false + end + + it 'saves a new reblog of a long-ago-reblogged status' do + account = Fabricate(:account) + reblogged = Fabricate(:status) + reblogs = 2.times.map { Fabricate(:status, reblog: reblogged) } + + # The first reblog will be accepted + FeedManager.instance.push('type', account, reblogs.first) + + # Fill the feed with intervening statuses + FeedManager::REBLOG_FALLOFF.times do + FeedManager.instance.push('type', account, Fabricate(:status)) + end + + # The second reblog should also be accepted + expect(FeedManager.instance.push('type', account, reblogs.last)).to be true + end + end + end + + describe '#unpush' do + it 'leaves a reblogged status when deleting the reblog' do + account = Fabricate(:account) + reblogged = Fabricate(:status) + status = Fabricate(:status, reblog: reblogged) + + FeedManager.instance.push('type', account, status) + + # The reblogging status should show up under normal conditions. + expect(Redis.current.zrange("feed:type:#{account.id}", 0, -1)).to eq [status.id.to_s] + + FeedManager.instance.unpush('type', account, status) + + # Because we couldn't tell if the status showed up any other way, + # we had to stick the reblogged status in by itself. + expect(Redis.current.zrange("feed:type:#{account.id}", 0, -1)).to eq [reblogged.id.to_s] + end + + it 'sends push updates' do + account = Fabricate(:account) + status = Fabricate(:status) + FeedManager.instance.push('type', account, status) + + allow(Redis.current).to receive_messages(publish: nil) + FeedManager.instance.unpush('type', account, status) + + deletion = Oj.dump(event: :delete, payload: status.id.to_s) + expect(Redis.current).to have_received(:publish).with("timeline:#{account.id}", deletion) + end end end diff --git a/spec/models/feed_spec.rb b/spec/models/feed_spec.rb index 1c377c17f..5433f44bd 100644 --- a/spec/models/feed_spec.rb +++ b/spec/models/feed_spec.rb @@ -9,7 +9,7 @@ RSpec.describe Feed, type: :model do Fabricate(:status, account: account, id: 3) Fabricate(:status, account: account, id: 10) Redis.current.zadd(FeedManager.instance.key(:home, account.id), - [[4, 'deleted'], [3, 'val3'], [2, 'val2'], [1, 'val1']]) + [[4, 4], [3, 3], [2, 2], [1, 1]]) feed = Feed.new(:home, account) results = feed.get(3) diff --git a/spec/services/batched_remove_status_service_spec.rb b/spec/services/batched_remove_status_service_spec.rb index f5c9adfb5..c82c45e09 100644 --- a/spec/services/batched_remove_status_service_spec.rb +++ b/spec/services/batched_remove_status_service_spec.rb @@ -5,7 +5,7 @@ RSpec.describe BatchedRemoveStatusService do let!(:alice) { Fabricate(:account) } let!(:bob) { Fabricate(:account, username: 'bob', domain: 'example.com', salmon_url: 'http://example.com/salmon') } - let!(:jeff) { Fabricate(:account) } + let!(:jeff) { Fabricate(:user).account } let!(:hank) { Fabricate(:account, username: 'hank', protocol: :activitypub, domain: 'example.com', inbox_url: 'http://example.com/inbox') } let(:status1) { PostStatusService.new.call(alice, 'Hello @bob@example.com') } @@ -19,6 +19,7 @@ RSpec.describe BatchedRemoveStatusService do stub_request(:post, 'http://example.com/inbox').to_return(status: 200) Fabricate(:subscription, account: alice, callback_url: 'http://example.com/push', confirmed: true, expires_at: 30.days.from_now) + jeff.user.update(current_sign_in_at: Time.now) jeff.follow!(alice) hank.follow!(alice) diff --git a/spec/services/precompute_feed_service_spec.rb b/spec/services/precompute_feed_service_spec.rb index dbd08ac1b..d1ef6c184 100644 --- a/spec/services/precompute_feed_service_spec.rb +++ b/spec/services/precompute_feed_service_spec.rb @@ -16,7 +16,7 @@ RSpec.describe PrecomputeFeedService do subject.call(account) - expect(Redis.current.zscore(FeedManager.instance.key(:home, account.id), reblog.id)).to eq status.id + expect(Redis.current.zscore(FeedManager.instance.key(:home, account.id), reblog.id)).to eq status.id.to_f end it 'does not raise an error even if it could not find any status' do -- cgit From b3af3f9f8cd5ed9c7ee06452e981b1b7734e1d89 Mon Sep 17 00:00:00 2001 From: utam0k Date: Wed, 4 Oct 2017 22:16:10 +0900 Subject: Implement EmailBlackList (#5109) * Implement BlacklistedEmailDomain * Use Faker::Internet.domain_name * Remove note column * Add frozen_string_literal comment * Delete unnecessary codes * Sort alphabetically * Change of wording * Rename BlacklistedEmailDomain to EmailDomainBlock --- .../admin/email_domain_blocks_controller.rb | 40 +++++++++++++++ app/models/email_domain_block.rb | 17 +++++++ app/validators/blacklisted_email_validator.rb | 1 + .../_email_domain_block.html.haml | 5 ++ .../admin/email_domain_blocks/index.html.haml | 13 +++++ app/views/admin/email_domain_blocks/new.html.haml | 10 ++++ config/locales/en.yml | 10 ++++ config/locales/ja.yml | 10 ++++ config/navigation.rb | 1 + config/routes.rb | 1 + .../20170928082043_create_email_domain_blocks.rb | 9 ++++ db/schema.rb | 8 ++- .../admin/email_domain_blocks_controller_spec.rb | 59 ++++++++++++++++++++++ spec/fabricators/email_domain_block_fabricator.rb | 3 ++ spec/models/email_domain_block_spec.rb | 21 ++++++++ 15 files changed, 207 insertions(+), 1 deletion(-) create mode 100644 app/controllers/admin/email_domain_blocks_controller.rb create mode 100644 app/models/email_domain_block.rb create mode 100644 app/views/admin/email_domain_blocks/_email_domain_block.html.haml create mode 100644 app/views/admin/email_domain_blocks/index.html.haml create mode 100644 app/views/admin/email_domain_blocks/new.html.haml create mode 100644 db/migrate/20170928082043_create_email_domain_blocks.rb create mode 100644 spec/controllers/admin/email_domain_blocks_controller_spec.rb create mode 100644 spec/fabricators/email_domain_block_fabricator.rb create mode 100644 spec/models/email_domain_block_spec.rb (limited to 'db') diff --git a/app/controllers/admin/email_domain_blocks_controller.rb b/app/controllers/admin/email_domain_blocks_controller.rb new file mode 100644 index 000000000..09275d5dc --- /dev/null +++ b/app/controllers/admin/email_domain_blocks_controller.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +module Admin + class EmailDomainBlocksController < BaseController + before_action :set_email_domain_block, only: [:show, :destroy] + + def index + @email_domain_blocks = EmailDomainBlock.page(params[:page]) + end + + def new + @email_domain_block = EmailDomainBlock.new + end + + def create + @email_domain_block = EmailDomainBlock.new(resource_params) + + if @email_domain_block.save + redirect_to admin_email_domain_blocks_path, notice: I18n.t('admin.email_domain_blocks.created_msg') + else + render :new + end + end + + def destroy + @email_domain_block.destroy + redirect_to admin_email_domain_blocks_path, notice: I18n.t('admin.email_domain_blocks.destroyed_msg') + end + + private + + def set_email_domain_block + @email_domain_block = EmailDomainBlock.find(params[:id]) + end + + def resource_params + params.require(:email_domain_block).permit(:domain) + end + end +end diff --git a/app/models/email_domain_block.rb b/app/models/email_domain_block.rb new file mode 100644 index 000000000..839038bea --- /dev/null +++ b/app/models/email_domain_block.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true +# == Schema Information +# +# Table name: email_domain_blocks +# +# id :integer not null, primary key +# domain :string not null +# created_at :datetime not null +# updated_at :datetime not null +# + +class EmailDomainBlock < ApplicationRecord + def self.block?(email) + domain = email.gsub(/.+@([^.]+)/, '\1') + where(domain: domain).exists? + end +end diff --git a/app/validators/blacklisted_email_validator.rb b/app/validators/blacklisted_email_validator.rb index 0ba79694b..3f203f49a 100644 --- a/app/validators/blacklisted_email_validator.rb +++ b/app/validators/blacklisted_email_validator.rb @@ -12,6 +12,7 @@ class BlacklistedEmailValidator < ActiveModel::Validator end def on_blacklist?(value) + return true if EmailDomainBlock.block?(value) return false if Rails.configuration.x.email_domains_blacklist.blank? domains = Rails.configuration.x.email_domains_blacklist.gsub('.', '\.') diff --git a/app/views/admin/email_domain_blocks/_email_domain_block.html.haml b/app/views/admin/email_domain_blocks/_email_domain_block.html.haml new file mode 100644 index 000000000..61cff9395 --- /dev/null +++ b/app/views/admin/email_domain_blocks/_email_domain_block.html.haml @@ -0,0 +1,5 @@ +%tr + %td.domain + %samp= email_domain_block.domain + %td + = table_link_to 'trash', t('admin.email_domain_blocks.delete'), admin_email_domain_block_path(email_domain_block), method: :delete diff --git a/app/views/admin/email_domain_blocks/index.html.haml b/app/views/admin/email_domain_blocks/index.html.haml new file mode 100644 index 000000000..fbdb3b80b --- /dev/null +++ b/app/views/admin/email_domain_blocks/index.html.haml @@ -0,0 +1,13 @@ +- content_for :page_title do + = t('admin.email_domain_blocks.title') + +%table.table + %thead + %tr + %th= t('admin.email_domain_blocks.domain') + %th + %tbody + = render @email_domain_blocks + += paginate @email_domain_blocks += link_to t('admin.email_domain_blocks.add_new'), new_admin_email_domain_block_path, class: 'button' diff --git a/app/views/admin/email_domain_blocks/new.html.haml b/app/views/admin/email_domain_blocks/new.html.haml new file mode 100644 index 000000000..bcae867d9 --- /dev/null +++ b/app/views/admin/email_domain_blocks/new.html.haml @@ -0,0 +1,10 @@ +- content_for :page_title do + = t('.title') + += simple_form_for @email_domain_block, url: admin_email_domain_blocks_path do |f| + = render 'shared/error_messages', object: @email_domain_block + + = f.input :domain, placeholder: t('admin.email_domain_blocks.domain') + + .actions + = f.button :button, t('.create'), type: :submit diff --git a/config/locales/en.yml b/config/locales/en.yml index 4a6df8cb2..5d9557535 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -152,6 +152,16 @@ en: undo: Undo title: Domain Blocks undo: Undo + email_domain_blocks: + add_new: Add new + created_msg: Email domain block successfully created + delete: Delete + destroyed_msg: Email domain block successfully deleted + domain: Domain + new: + create: Create block + title: New email domain block + title: Email Domain Block instances: account_count: Known accounts domain_name: Domain diff --git a/config/locales/ja.yml b/config/locales/ja.yml index d637a99ea..3d6f2fd0b 100644 --- a/config/locales/ja.yml +++ b/config/locales/ja.yml @@ -152,6 +152,16 @@ ja: undo: 元に戻す title: ドメインブロック undo: 元に戻す + email_domain_blocks: + add_new: 新規追加 + created_msg: 処理を完了しました + delete: 消去 + destroyed_msg: 消去しました + domain: ドメイン + new: + create: ブロックを作成 + title: 新規メールドメインブロック + title: メールドメインブロック instances: account_count: 既知のアカウント数 domain_name: ドメイン名 diff --git a/config/navigation.rb b/config/navigation.rb index 215d843b9..50bfbd480 100644 --- a/config/navigation.rb +++ b/config/navigation.rb @@ -26,6 +26,7 @@ SimpleNavigation::Configuration.run do |navigation| admin.item :instances, safe_join([fa_icon('cloud fw'), t('admin.instances.title')]), admin_instances_url, highlights_on: %r{/admin/instances} admin.item :subscriptions, safe_join([fa_icon('paper-plane-o fw'), t('admin.subscriptions.title')]), admin_subscriptions_url admin.item :domain_blocks, safe_join([fa_icon('lock fw'), t('admin.domain_blocks.title')]), admin_domain_blocks_url, highlights_on: %r{/admin/domain_blocks} + admin.item :email_domain_blocks, safe_join([fa_icon('envelope fw'), t('admin.email_domain_blocks.title')]), admin_email_domain_blocks_url, highlights_on: %r{/admin/email_domain_blocks} admin.item :sidekiq, safe_join([fa_icon('diamond fw'), 'Sidekiq']), sidekiq_url, link_html: { target: 'sidekiq' } admin.item :pghero, safe_join([fa_icon('database fw'), 'PgHero']), pghero_url, link_html: { target: 'pghero' } admin.item :settings, safe_join([fa_icon('cogs fw'), t('admin.settings.title')]), edit_admin_settings_url diff --git a/config/routes.rb b/config/routes.rb index 8e80e1510..959afc23f 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -108,6 +108,7 @@ Rails.application.routes.draw do namespace :admin do resources :subscriptions, only: [:index] resources :domain_blocks, only: [:index, :new, :create, :show, :destroy] + resources :email_domain_blocks, only: [:index, :new, :create, :destroy] resource :settings, only: [:edit, :update] resources :instances, only: [:index] do diff --git a/db/migrate/20170928082043_create_email_domain_blocks.rb b/db/migrate/20170928082043_create_email_domain_blocks.rb new file mode 100644 index 000000000..1f0fb7587 --- /dev/null +++ b/db/migrate/20170928082043_create_email_domain_blocks.rb @@ -0,0 +1,9 @@ +class CreateEmailDomainBlocks < ActiveRecord::Migration[5.1] + def change + create_table :email_domain_blocks do |t| + t.string :domain, null: false + + t.timestamps + end + end +end diff --git a/db/schema.rb b/db/schema.rb index 00cc24bae..337678c67 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20170927215609) do +ActiveRecord::Schema.define(version: 20170928082043) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -110,6 +110,12 @@ ActiveRecord::Schema.define(version: 20170927215609) do t.index ["domain"], name: "index_domain_blocks_on_domain", unique: true end + create_table "email_domain_blocks", force: :cascade do |t| + t.string "domain", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + create_table "favourites", force: :cascade do |t| t.datetime "created_at", null: false t.datetime "updated_at", null: false diff --git a/spec/controllers/admin/email_domain_blocks_controller_spec.rb b/spec/controllers/admin/email_domain_blocks_controller_spec.rb new file mode 100644 index 000000000..295de9073 --- /dev/null +++ b/spec/controllers/admin/email_domain_blocks_controller_spec.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Admin::EmailDomainBlocksController, type: :controller do + render_views + + before do + sign_in Fabricate(:user, admin: true), scope: :user + end + + describe 'GET #index' do + around do |example| + default_per_page = EmailDomainBlock.default_per_page + EmailDomainBlock.paginates_per 1 + example.run + EmailDomainBlock.paginates_per default_per_page + end + + it 'renders email blacks' do + 2.times { Fabricate(:email_domain_block) } + + get :index, params: { page: 2 } + + assigned = assigns(:email_domain_blocks) + expect(assigned.count).to eq 1 + expect(assigned.klass).to be EmailDomainBlock + expect(response).to have_http_status(:success) + end + end + + describe 'GET #new' do + it 'assigns a new email black' do + get :new + + expect(assigns(:email_domain_block)).to be_instance_of(EmailDomainBlock) + expect(response).to have_http_status(:success) + end + end + + describe 'POST #create' do + it 'blocks the domain when succeeded to save' do + post :create, params: { email_domain_block: { domain: 'example.com'} } + + expect(flash[:notice]).to eq I18n.t('admin.email_domain_blocks.created_msg') + expect(response).to redirect_to(admin_email_domain_blocks_path) + end + end + + describe 'DELETE #destroy' do + it 'unblocks the domain' do + email_domain_block = Fabricate(:email_domain_block) + delete :destroy, params: { id: email_domain_block.id } + + expect(flash[:notice]).to eq I18n.t('admin.email_domain_blocks.destroyed_msg') + expect(response).to redirect_to(admin_email_domain_blocks_path) + end + end +end diff --git a/spec/fabricators/email_domain_block_fabricator.rb b/spec/fabricators/email_domain_block_fabricator.rb new file mode 100644 index 000000000..d18af6433 --- /dev/null +++ b/spec/fabricators/email_domain_block_fabricator.rb @@ -0,0 +1,3 @@ +Fabricator(:email_domain_block) do + domain { sequence(:domain) { |i| "#{i}#{Faker::Internet.domain_name}" } } +end diff --git a/spec/models/email_domain_block_spec.rb b/spec/models/email_domain_block_spec.rb new file mode 100644 index 000000000..5f5d189d9 --- /dev/null +++ b/spec/models/email_domain_block_spec.rb @@ -0,0 +1,21 @@ +require 'rails_helper' + +RSpec.describe EmailDomainBlock, type: :model do + describe 'validations' do + it 'has a valid fabricator' do + email_domain_block = Fabricate.build(:email_domain_block) + expect(email_domain_block).to be_valid + end + end + + describe 'block?' do + it 'returns true if the domain is registed' do + Fabricate(:email_domain_block, domain: 'example.com') + expect(EmailDomainBlock.block?('nyarn@example.com')).to eq true + end + it 'returns true if the domain is not registed' do + Fabricate(:email_domain_block, domain: 'domain') + expect(EmailDomainBlock.block?('example')).to eq false + end + end +end -- cgit From 49cc0eb3e7d1521079e33a60216df46679082547 Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Thu, 5 Oct 2017 23:42:05 +0200 Subject: Improve admin UI for custom emojis, add copy/disable/enable (#5231) --- app/controllers/admin/custom_emojis_controller.rb | 42 ++++- app/controllers/api/v1/custom_emojis_controller.rb | 2 +- app/models/account_filter.rb | 2 + app/models/custom_emoji.rb | 11 +- app/models/custom_emoji_filter.rb | 34 ++++ .../admin/custom_emojis/_custom_emoji.html.haml | 13 ++ app/views/admin/custom_emojis/index.html.haml | 20 +++ config/brakeman.ignore | 182 ++++++++++++++++++++- config/locales/de.yml | 6 +- config/locales/en.yml | 7 + config/routes.rb | 8 +- ...20171005171936_add_disabled_to_custom_emojis.rb | 15 ++ db/schema.rb | 3 +- 13 files changed, 330 insertions(+), 15 deletions(-) create mode 100644 app/models/custom_emoji_filter.rb create mode 100644 db/migrate/20171005171936_add_disabled_to_custom_emojis.rb (limited to 'db') diff --git a/app/controllers/admin/custom_emojis_controller.rb b/app/controllers/admin/custom_emojis_controller.rb index d70514d9a..dba9f1012 100644 --- a/app/controllers/admin/custom_emojis_controller.rb +++ b/app/controllers/admin/custom_emojis_controller.rb @@ -2,8 +2,10 @@ module Admin class CustomEmojisController < BaseController + before_action :set_custom_emoji, except: [:index, :new, :create] + def index - @custom_emojis = CustomEmoji.local + @custom_emojis = filtered_custom_emojis.page(params[:page]) end def new @@ -21,14 +23,50 @@ module Admin end def destroy - CustomEmoji.find(params[:id]).destroy + @custom_emoji.destroy redirect_to admin_custom_emojis_path, notice: I18n.t('admin.custom_emojis.destroyed_msg') end + def copy + emoji = @custom_emoji.dup + emoji.domain = nil + + if emoji.save + redirect_to admin_custom_emojis_path, notice: I18n.t('admin.custom_emojis.copied_msg') + else + redirect_to admin_custom_emojis_path, alert: I18n.t('admin.custom_emojis.copy_failed_msg') + end + end + + def enable + @custom_emoji.update!(disabled: false) + redirect_to admin_custom_emojis_path, notice: I18n.t('admin.custom_emojis.enabled_msg') + end + + def disable + @custom_emoji.update!(disabled: true) + redirect_to admin_custom_emojis_path, notice: I18n.t('admin.custom_emojis.disabled_msg') + end + private + def set_custom_emoji + @custom_emoji = CustomEmoji.find(params[:id]) + end + def resource_params params.require(:custom_emoji).permit(:shortcode, :image) end + + def filtered_custom_emojis + CustomEmojiFilter.new(filter_params).results + end + + def filter_params + params.permit( + :local, + :remote + ) + end end end diff --git a/app/controllers/api/v1/custom_emojis_controller.rb b/app/controllers/api/v1/custom_emojis_controller.rb index 4dd77fb55..f8cd64455 100644 --- a/app/controllers/api/v1/custom_emojis_controller.rb +++ b/app/controllers/api/v1/custom_emojis_controller.rb @@ -4,6 +4,6 @@ class Api::V1::CustomEmojisController < Api::BaseController respond_to :json def index - render json: CustomEmoji.local, each_serializer: REST::CustomEmojiSerializer + render json: CustomEmoji.local.where(disabled: false), each_serializer: REST::CustomEmojiSerializer end end diff --git a/app/models/account_filter.rb b/app/models/account_filter.rb index 1a8cc5192..189872368 100644 --- a/app/models/account_filter.rb +++ b/app/models/account_filter.rb @@ -9,9 +9,11 @@ class AccountFilter def results scope = Account.alphabetic + params.each do |key, value| scope.merge!(scope_for(key, value)) if value.present? end + scope end diff --git a/app/models/custom_emoji.rb b/app/models/custom_emoji.rb index 9e9be5e12..258b50c82 100644 --- a/app/models/custom_emoji.rb +++ b/app/models/custom_emoji.rb @@ -12,6 +12,7 @@ # image_updated_at :datetime # created_at :datetime not null # updated_at :datetime not null +# disabled :boolean default(FALSE), not null # class CustomEmoji < ApplicationRecord @@ -26,10 +27,16 @@ class CustomEmoji < ApplicationRecord validates_attachment :image, content_type: { content_type: 'image/png' }, presence: true, size: { in: 0..50.kilobytes } validates :shortcode, uniqueness: { scope: :domain }, format: { with: /\A#{SHORTCODE_RE_FRAGMENT}\z/ }, length: { minimum: 2 } - scope :local, -> { where(domain: nil) } + scope :local, -> { where(domain: nil) } + scope :remote, -> { where.not(domain: nil) } + scope :alphabetic, -> { order(domain: :asc, shortcode: :asc) } include Remotable + def local? + domain.nil? + end + class << self def from_text(text, domain) return [] if text.blank? @@ -38,7 +45,7 @@ class CustomEmoji < ApplicationRecord return [] if shortcodes.empty? - where(shortcode: shortcodes, domain: domain) + where(shortcode: shortcodes, domain: domain, disabled: false) end end end diff --git a/app/models/custom_emoji_filter.rb b/app/models/custom_emoji_filter.rb new file mode 100644 index 000000000..2d1394a59 --- /dev/null +++ b/app/models/custom_emoji_filter.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +class CustomEmojiFilter + attr_reader :params + + def initialize(params) + @params = params + end + + def results + scope = CustomEmoji.alphabetic + + params.each do |key, value| + scope.merge!(scope_for(key, value)) if value.present? + end + + scope + end + + private + + def scope_for(key, value) + case key.to_s + when 'local' + CustomEmoji.local + when 'remote' + CustomEmoji.remote + when 'by_domain' + CustomEmoji.where(domain: value) + else + raise "Unknown filter: #{key}" + end + end +end diff --git a/app/views/admin/custom_emojis/_custom_emoji.html.haml b/app/views/admin/custom_emojis/_custom_emoji.html.haml index ff1aa9925..53263c43f 100644 --- a/app/views/admin/custom_emojis/_custom_emoji.html.haml +++ b/app/views/admin/custom_emojis/_custom_emoji.html.haml @@ -3,5 +3,18 @@ = image_tag custom_emoji.image.url, class: 'emojione', alt: ":#{custom_emoji.shortcode}:" %td %samp= ":#{custom_emoji.shortcode}:" + %td + - if custom_emoji.local? + = t('admin.accounts.location.local') + - else + = custom_emoji.domain + %td + - unless custom_emoji.local? + = table_link_to 'copy', t('admin.custom_emojis.copy'), copy_admin_custom_emoji_path(custom_emoji), method: :post + %td + - if custom_emoji.disabled? + = table_link_to 'power-off', t('admin.custom_emojis.enable'), enable_admin_custom_emoji_path(custom_emoji), method: :post, data: { confirm: t('admin.accounts.are_you_sure') } + - else + = table_link_to 'power-off', t('admin.custom_emojis.disable'), disable_admin_custom_emoji_path(custom_emoji), method: :post, data: { confirm: t('admin.accounts.are_you_sure') } %td = table_link_to 'times', t('admin.custom_emojis.delete'), admin_custom_emoji_path(custom_emoji), method: :delete, data: { confirm: t('admin.accounts.are_you_sure') } diff --git a/app/views/admin/custom_emojis/index.html.haml b/app/views/admin/custom_emojis/index.html.haml index d5f32e84b..20ffb8529 100644 --- a/app/views/admin/custom_emojis/index.html.haml +++ b/app/views/admin/custom_emojis/index.html.haml @@ -1,14 +1,34 @@ - content_for :page_title do = t('admin.custom_emojis.title') +.filters + .filter-subset + %strong= t('admin.accounts.location.title') + %ul + %li= filter_link_to t('admin.accounts.location.all'), local: nil, remote: nil + %li + - if selected? local: '1', remote: nil + = filter_link_to t('admin.accounts.location.local'), {local: nil, remote: nil}, {local: '1', remote: nil} + - else + = filter_link_to t('admin.accounts.location.local'), local: '1', remote: nil + %li + - if selected? remote: '1', local: nil + = filter_link_to t('admin.accounts.location.remote'), {remote: nil, local: nil}, {remote: '1', local: nil} + - else + = filter_link_to t('admin.accounts.location.remote'), remote: '1', local: nil + .table-wrapper %table.table %thead %tr %th= t('admin.custom_emojis.emoji') %th= t('admin.custom_emojis.shortcode') + %th= t('admin.accounts.domain') + %th + %th %th %tbody = render @custom_emojis += paginate @custom_emojis = link_to t('admin.custom_emojis.upload'), new_admin_custom_emoji_path, class: 'button' diff --git a/config/brakeman.ignore b/config/brakeman.ignore index dbb59dd07..ed6e121d2 100644 --- a/config/brakeman.ignore +++ b/config/brakeman.ignore @@ -1,5 +1,81 @@ { "ignored_warnings": [ + { + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "0adbe361b91afff22ba51e5fc2275ec703cc13255a0cb3eecd8dab223ab9f61e", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in link_to href", + "file": "app/views/admin/accounts/show.html.haml", + "line": 122, + "link": "http://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(Account.find(params[:id]).inbox_url, Account.find(params[:id]).inbox_url)", + "render_path": [{"type":"controller","class":"Admin::AccountsController","method":"show","line":13,"file":"app/controllers/admin/accounts_controller.rb"}], + "location": { + "type": "template", + "template": "admin/accounts/show" + }, + "user_input": "Account.find(params[:id]).inbox_url", + "confidence": "Weak", + "note": "" + }, + { + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "1fc29c578d0c89bf13bd5476829d272d54cd06b92ccf6df18568fa1f2674926e", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in link_to href", + "file": "app/views/admin/accounts/show.html.haml", + "line": 128, + "link": "http://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(Account.find(params[:id]).shared_inbox_url, Account.find(params[:id]).shared_inbox_url)", + "render_path": [{"type":"controller","class":"Admin::AccountsController","method":"show","line":13,"file":"app/controllers/admin/accounts_controller.rb"}], + "location": { + "type": "template", + "template": "admin/accounts/show" + }, + "user_input": "Account.find(params[:id]).shared_inbox_url", + "confidence": "Weak", + "note": "" + }, + { + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "2129d4c1e63a351d28d8d2937ff0b50237809c3df6725c0c5ef82b881dbb2086", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in link_to href", + "file": "app/views/admin/accounts/show.html.haml", + "line": 35, + "link": "http://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(Account.find(params[:id]).url, Account.find(params[:id]).url)", + "render_path": [{"type":"controller","class":"Admin::AccountsController","method":"show","line":13,"file":"app/controllers/admin/accounts_controller.rb"}], + "location": { + "type": "template", + "template": "admin/accounts/show" + }, + "user_input": "Account.find(params[:id]).url", + "confidence": "Weak", + "note": "" + }, + { + "warning_type": "Dynamic Render Path", + "warning_code": 15, + "fingerprint": "3b0a20b08aef13cf8cf865384fae0cfd3324d8200a83262bf4abbc8091b5fec5", + "check_name": "Render", + "message": "Render path contains parameter value", + "file": "app/views/admin/custom_emojis/index.html.haml", + "line": 31, + "link": "http://brakemanscanner.org/docs/warning_types/dynamic_render_path/", + "code": "render(action => filtered_custom_emojis.page(params[:page]), {})", + "render_path": [{"type":"controller","class":"Admin::CustomEmojisController","method":"index","line":9,"file":"app/controllers/admin/custom_emojis_controller.rb"}], + "location": { + "type": "template", + "template": "admin/custom_emojis/index" + }, + "user_input": "params[:page]", + "confidence": "Weak", + "note": "" + }, { "warning_type": "Dynamic Render Path", "warning_code": 15, @@ -19,6 +95,44 @@ "confidence": "Weak", "note": "" }, + { + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "64b5b2a02ede9c2b3598881eb5a466d63f7d27fe0946aa00d570111ec7338d2e", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in link_to href", + "file": "app/views/admin/accounts/show.html.haml", + "line": 131, + "link": "http://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(Account.find(params[:id]).followers_url, Account.find(params[:id]).followers_url)", + "render_path": [{"type":"controller","class":"Admin::AccountsController","method":"show","line":13,"file":"app/controllers/admin/accounts_controller.rb"}], + "location": { + "type": "template", + "template": "admin/accounts/show" + }, + "user_input": "Account.find(params[:id]).followers_url", + "confidence": "Weak", + "note": "" + }, + { + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "82f7b0d09beb3ab68e0fa16be63cedf4e820f2490326e9a1cec05761d92446cd", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in link_to href", + "file": "app/views/admin/accounts/show.html.haml", + "line": 106, + "link": "http://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(Account.find(params[:id]).salmon_url, Account.find(params[:id]).salmon_url)", + "render_path": [{"type":"controller","class":"Admin::AccountsController","method":"show","line":13,"file":"app/controllers/admin/accounts_controller.rb"}], + "location": { + "type": "template", + "template": "admin/accounts/show" + }, + "user_input": "Account.find(params[:id]).salmon_url", + "confidence": "Weak", + "note": "" + }, { "warning_type": "Dynamic Render Path", "warning_code": 15, @@ -26,7 +140,7 @@ "check_name": "Render", "message": "Render path contains parameter value", "file": "app/views/admin/accounts/index.html.haml", - "line": 63, + "line": 64, "link": "http://brakemanscanner.org/docs/warning_types/dynamic_render_path/", "code": "render(action => filtered_accounts.page(params[:page]), {})", "render_path": [{"type":"controller","class":"Admin::AccountsController","method":"index","line":10,"file":"app/controllers/admin/accounts_controller.rb"}], @@ -38,6 +152,25 @@ "confidence": "Weak", "note": "" }, + { + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "bb0ad5c4a42e06e3846c2089ff5269c17f65483a69414f6ce65eecf2bb11fab7", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in link_to href", + "file": "app/views/admin/accounts/show.html.haml", + "line": 95, + "link": "http://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(Account.find(params[:id]).remote_url, Account.find(params[:id]).remote_url)", + "render_path": [{"type":"controller","class":"Admin::AccountsController","method":"show","line":13,"file":"app/controllers/admin/accounts_controller.rb"}], + "location": { + "type": "template", + "template": "admin/accounts/show" + }, + "user_input": "Account.find(params[:id]).remote_url", + "confidence": "Weak", + "note": "" + }, { "warning_type": "Redirect", "warning_code": 18, @@ -65,7 +198,7 @@ "check_name": "Render", "message": "Render path contains parameter value", "file": "app/views/admin/reports/index.html.haml", - "line": 24, + "line": 25, "link": "http://brakemanscanner.org/docs/warning_types/dynamic_render_path/", "code": "render(action => filtered_reports.page(params[:page]), {})", "render_path": [{"type":"controller","class":"Admin::ReportsController","method":"index","line":9,"file":"app/controllers/admin/reports_controller.rb"}], @@ -77,6 +210,45 @@ "confidence": "Weak", "note": "" }, + { + "warning_type": "SQL Injection", + "warning_code": 0, + "fingerprint": "cd440d9d0bcb76225f4142030cec0bdec6ad119c537c108c9d514bf87bc34d29", + "check_name": "SQL", + "message": "Possible SQL injection", + "file": "lib/mastodon/timestamp_ids.rb", + "line": 69, + "link": "http://brakemanscanner.org/docs/warning_types/sql_injection/", + "code": "ActiveRecord::Base.connection.execute(\" CREATE OR REPLACE FUNCTION timestamp_id(table_name text)\\n RETURNS bigint AS\\n $$\\n DECLARE\\n time_part bigint;\\n sequence_base bigint;\\n tail bigint;\\n BEGIN\\n -- Our ID will be composed of the following:\\n -- 6 bytes (48 bits) of millisecond-level timestamp\\n -- 2 bytes (16 bits) of sequence data\\n\\n -- The 'sequence data' is intended to be unique within a\\n -- given millisecond, yet obscure the 'serial number' of\\n -- this row.\\n\\n -- To do this, we hash the following data:\\n -- * Table name (if provided, skipped if not)\\n -- * Secret salt (should not be guessable)\\n -- * Timestamp (again, millisecond-level granularity)\\n\\n -- We then take the first two bytes of that value, and add\\n -- the lowest two bytes of the table ID sequence number\\n -- (`table_name`_id_seq). This means that even if we insert\\n -- two rows at the same millisecond, they will have\\n -- distinct 'sequence data' portions.\\n\\n -- If this happens, and an attacker can see both such IDs,\\n -- they can determine which of the two entries was inserted\\n -- first, but not the total number of entries in the table\\n -- (even mod 2**16).\\n\\n -- The table name is included in the hash to ensure that\\n -- different tables derive separate sequence bases so rows\\n -- inserted in the same millisecond in different tables do\\n -- not reveal the table ID sequence number for one another.\\n\\n -- The secret salt is included in the hash to ensure that\\n -- external users cannot derive the sequence base given the\\n -- timestamp and table name, which would allow them to\\n -- compute the table ID sequence number.\\n\\n time_part := (\\n -- Get the time in milliseconds\\n ((date_part('epoch', now()) * 1000))::bigint\\n -- And shift it over two bytes\\n << 16);\\n\\n sequence_base := (\\n 'x' ||\\n -- Take the first two bytes (four hex characters)\\n substr(\\n -- Of the MD5 hash of the data we documented\\n md5(table_name ||\\n '#{SecureRandom.hex(16)}' ||\\n time_part::text\\n ),\\n 1, 4\\n )\\n -- And turn it into a bigint\\n )::bit(16)::bigint;\\n\\n -- Finally, add our sequence number to our base, and chop\\n -- it to the last two bytes\\n tail := (\\n (sequence_base + nextval(table_name || '_id_seq'))\\n & 65535);\\n\\n -- Return the time part and the sequence part. OR appears\\n -- faster here than addition, but they're equivalent:\\n -- time_part has no trailing two bytes, and tail is only\\n -- the last two bytes.\\n RETURN time_part | tail;\\n END\\n $$ LANGUAGE plpgsql VOLATILE;\\n\")", + "render_path": null, + "location": { + "type": "method", + "class": "Mastodon::TimestampIds", + "method": "s(:self).define_timestamp_id" + }, + "user_input": "SecureRandom.hex(16)", + "confidence": "Medium", + "note": "" + }, + { + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "e04aafe1e06cf8317fb6ac0a7f35783e45aa1274272ee6eaf28d39adfdad489b", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in link_to href", + "file": "app/views/admin/accounts/show.html.haml", + "line": 125, + "link": "http://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(Account.find(params[:id]).outbox_url, Account.find(params[:id]).outbox_url)", + "render_path": [{"type":"controller","class":"Admin::AccountsController","method":"show","line":13,"file":"app/controllers/admin/accounts_controller.rb"}], + "location": { + "type": "template", + "template": "admin/accounts/show" + }, + "user_input": "Account.find(params[:id]).outbox_url", + "confidence": "Weak", + "note": "" + }, { "warning_type": "Dynamic Render Path", "warning_code": 15, @@ -84,7 +256,7 @@ "check_name": "Render", "message": "Render path contains parameter value", "file": "app/views/stream_entries/show.html.haml", - "line": 23, + "line": 21, "link": "http://brakemanscanner.org/docs/warning_types/dynamic_render_path/", "code": "render(partial => \"stream_entries/#{Account.find_local!(params[:account_username]).statuses.find(params[:id]).stream_entry.activity_type.downcase}\", { :locals => ({ Account.find_local!(params[:account_username]).statuses.find(params[:id]).stream_entry.activity_type.downcase.to_sym => Account.find_local!(params[:account_username]).statuses.find(params[:id]).stream_entry.activity, :include_threads => true }) })", "render_path": [{"type":"controller","class":"StatusesController","method":"show","line":20,"file":"app/controllers/statuses_controller.rb"}], @@ -97,6 +269,6 @@ "note": "" } ], - "updated": "2017-08-30 05:14:04 +0200", - "brakeman_version": "3.7.2" + "updated": "2017-10-05 20:06:40 +0200", + "brakeman_version": "4.0.1" } diff --git a/config/locales/de.yml b/config/locales/de.yml index ec48bd5ff..7c0edff94 100644 --- a/config/locales/de.yml +++ b/config/locales/de.yml @@ -137,7 +137,7 @@ de: reject_media: Mediendateien ablehnen reject_media_hint: Entfernt lokal gespeicherte Mediendateien und verhindert deren künftiges Herunterladen. Für Sperren irrelevant severities: - none: Kein + noop: Kein silence: Stummschaltung suspend: Sperren severity: Schweregrad @@ -180,7 +180,7 @@ de: nsfw: 'false': Medienanhänge wieder anzeigen 'true': Medienanhänge verbergen - report: "Meldung #%{id}" + report: 'Meldung #%{id}' report_contents: Inhalt reported_account: Gemeldetes Konto reported_by: Gemeldet von @@ -386,7 +386,7 @@ de: body: "%{name} hat dich erwähnt:" subject: "%{name} hat dich erwähnt" reblog: - body: '%{name} hat deinen Beitrag geteilt:' + body: "%{name} hat deinen Beitrag geteilt:" subject: "%{name} hat deinen Beitrag geteilt" number: human: diff --git a/config/locales/en.yml b/config/locales/en.yml index 5d9557535..2059c5e2b 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -109,10 +109,17 @@ en: username: Username web: Web custom_emojis: + copied_msg: Successfully created local copy of the emoji + copy: Copy + copy_failed_msg: Could not make a local copy of that emoji created_msg: Emoji successfully created! delete: Delete destroyed_msg: Emojo successfully destroyed! + disable: Disable + disabled_msg: Successfully disabled that emoji emoji: Emoji + enable: Enable + enabled_msg: Successfully enabled that emoji image_hint: PNG up to 50KB new: title: Add new custom emoji diff --git a/config/routes.rb b/config/routes.rb index 959afc23f..cc1f66e52 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -139,7 +139,13 @@ Rails.application.routes.draw do resource :two_factor_authentication, only: [:destroy] end - resources :custom_emojis, only: [:index, :new, :create, :destroy] + resources :custom_emojis, only: [:index, :new, :create, :destroy] do + member do + post :copy + post :enable + post :disable + end + end end get '/admin', to: redirect('/admin/settings/edit', status: 302) diff --git a/db/migrate/20171005171936_add_disabled_to_custom_emojis.rb b/db/migrate/20171005171936_add_disabled_to_custom_emojis.rb new file mode 100644 index 000000000..067a7bee0 --- /dev/null +++ b/db/migrate/20171005171936_add_disabled_to_custom_emojis.rb @@ -0,0 +1,15 @@ +require Rails.root.join('lib', 'mastodon', 'migration_helpers') + +class AddDisabledToCustomEmojis < ActiveRecord::Migration[5.1] + include Mastodon::MigrationHelpers + + disable_ddl_transaction! + + def up + safety_assured { add_column_with_default :custom_emojis, :disabled, :bool, default: false } + end + + def down + remove_column :custom_emojis, :disabled + end +end diff --git a/db/schema.rb b/db/schema.rb index 337678c67..3358e2997 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20170928082043) do +ActiveRecord::Schema.define(version: 20171005171936) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -98,6 +98,7 @@ ActiveRecord::Schema.define(version: 20170928082043) do t.datetime "image_updated_at" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.boolean "disabled", default: false, null: false t.index ["shortcode", "domain"], name: "index_custom_emojis_on_shortcode_and_domain", unique: true end -- cgit From 3a3475450e46f670e8beaf4bf804b820ad39a5f9 Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Sat, 7 Oct 2017 17:43:42 +0200 Subject: Encode custom emojis as resolveable objects in ActivityPub (#5243) * Encode custom emojis as resolveable objects in ActivityPub * Improve code style --- app/controllers/accounts_controller.rb | 5 +++- app/controllers/emojis_controller.rb | 22 ++++++++++++++++ app/controllers/follower_accounts_controller.rb | 5 +++- app/controllers/following_accounts_controller.rb | 5 +++- app/controllers/statuses_controller.rb | 10 ++++++-- app/controllers/tags_controller.rb | 5 +++- app/lib/activitypub/activity/create.rb | 12 ++++++--- app/lib/activitypub/tag_manager.rb | 2 ++ app/models/custom_emoji.rb | 6 +++++ app/serializers/activitypub/actor_serializer.rb | 18 ++------------ app/serializers/activitypub/emoji_serializer.rb | 29 ++++++++++++++++++++++ app/serializers/activitypub/image_serializer.rb | 19 ++++++++++++++ app/serializers/activitypub/note_serializer.rb | 17 +------------ config/routes.rb | 5 ++-- .../20171006142024_add_uri_to_custom_emojis.rb | 6 +++++ db/schema.rb | 4 ++- spec/lib/activitypub/activity/create_spec.rb | 10 +++++--- 17 files changed, 132 insertions(+), 48 deletions(-) create mode 100644 app/controllers/emojis_controller.rb create mode 100644 app/serializers/activitypub/emoji_serializer.rb create mode 100644 app/serializers/activitypub/image_serializer.rb create mode 100644 db/migrate/20171006142024_add_uri_to_custom_emojis.rb (limited to 'db') diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb index 26ab6636b..75915b337 100644 --- a/app/controllers/accounts_controller.rb +++ b/app/controllers/accounts_controller.rb @@ -26,7 +26,10 @@ class AccountsController < ApplicationController end format.json do - render json: @account, serializer: ActivityPub::ActorSerializer, adapter: ActivityPub::Adapter, content_type: 'application/activity+json' + render json: @account, + serializer: ActivityPub::ActorSerializer, + adapter: ActivityPub::Adapter, + content_type: 'application/activity+json' end end end diff --git a/app/controllers/emojis_controller.rb b/app/controllers/emojis_controller.rb new file mode 100644 index 000000000..a82b9340b --- /dev/null +++ b/app/controllers/emojis_controller.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +class EmojisController < ApplicationController + before_action :set_emoji + + def show + respond_to do |format| + format.json do + render json: @emoji, + serializer: ActivityPub::EmojiSerializer, + adapter: ActivityPub::Adapter, + content_type: 'application/activity+json' + end + end + end + + private + + def set_emoji + @emoji = CustomEmoji.local.find(params[:id]) + end +end diff --git a/app/controllers/follower_accounts_controller.rb b/app/controllers/follower_accounts_controller.rb index 8eb4d2822..399e79665 100644 --- a/app/controllers/follower_accounts_controller.rb +++ b/app/controllers/follower_accounts_controller.rb @@ -10,7 +10,10 @@ class FollowerAccountsController < ApplicationController format.html format.json do - render json: collection_presenter, serializer: ActivityPub::CollectionSerializer, adapter: ActivityPub::Adapter, content_type: 'application/activity+json' + render json: collection_presenter, + serializer: ActivityPub::CollectionSerializer, + adapter: ActivityPub::Adapter, + content_type: 'application/activity+json' end end end diff --git a/app/controllers/following_accounts_controller.rb b/app/controllers/following_accounts_controller.rb index 1ca6f0fe7..1e73d4bd4 100644 --- a/app/controllers/following_accounts_controller.rb +++ b/app/controllers/following_accounts_controller.rb @@ -10,7 +10,10 @@ class FollowingAccountsController < ApplicationController format.html format.json do - render json: collection_presenter, serializer: ActivityPub::CollectionSerializer, adapter: ActivityPub::Adapter, content_type: 'application/activity+json' + render json: collection_presenter, + serializer: ActivityPub::CollectionSerializer, + adapter: ActivityPub::Adapter, + content_type: 'application/activity+json' end end end diff --git a/app/controllers/statuses_controller.rb b/app/controllers/statuses_controller.rb index 65206ea96..e8a360fb5 100644 --- a/app/controllers/statuses_controller.rb +++ b/app/controllers/statuses_controller.rb @@ -21,13 +21,19 @@ class StatusesController < ApplicationController end format.json do - render json: @status, serializer: ActivityPub::NoteSerializer, adapter: ActivityPub::Adapter, content_type: 'application/activity+json' + render json: @status, + serializer: ActivityPub::NoteSerializer, + adapter: ActivityPub::Adapter, + content_type: 'application/activity+json' end end end def activity - render json: @status, serializer: ActivityPub::ActivitySerializer, adapter: ActivityPub::Adapter, content_type: 'application/activity+json' + render json: @status, + serializer: ActivityPub::ActivitySerializer, + adapter: ActivityPub::Adapter, + content_type: 'application/activity+json' end def embed diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index 3001b2ee3..240ef058a 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -12,7 +12,10 @@ class TagsController < ApplicationController format.html format.json do - render json: collection_presenter, serializer: ActivityPub::CollectionSerializer, adapter: ActivityPub::Adapter, content_type: 'application/activity+json' + render json: collection_presenter, + serializer: ActivityPub::CollectionSerializer, + adapter: ActivityPub::Adapter, + content_type: 'application/activity+json' end end end diff --git a/app/lib/activitypub/activity/create.rb b/app/lib/activitypub/activity/create.rb index be656de48..9421a0aa7 100644 --- a/app/lib/activitypub/activity/create.rb +++ b/app/lib/activitypub/activity/create.rb @@ -86,15 +86,19 @@ class ActivityPub::Activity::Create < ActivityPub::Activity end def process_emoji(tag, _status) - return if tag['name'].blank? || tag['href'].blank? + return if skip_download? + return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank? shortcode = tag['name'].delete(':') + image_url = tag['icon']['url'] + uri = tag['id'] + updated = tag['updated'] emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain) - return if !emoji.nil? || skip_download? + return unless emoji.nil? || emoji.updated_at >= updated - emoji = CustomEmoji.new(domain: @account.domain, shortcode: shortcode) - emoji.image_remote_url = tag['href'] + emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri) + emoji.image_remote_url = image_url emoji.save end diff --git a/app/lib/activitypub/tag_manager.rb b/app/lib/activitypub/tag_manager.rb index 4ec3b8c56..0708713e6 100644 --- a/app/lib/activitypub/tag_manager.rb +++ b/app/lib/activitypub/tag_manager.rb @@ -33,6 +33,8 @@ class ActivityPub::TagManager when :note, :comment, :activity return activity_account_status_url(target.account, target) if target.reblog? account_status_url(target.account, target) + when :emoji + emoji_url(target) end end diff --git a/app/models/custom_emoji.rb b/app/models/custom_emoji.rb index 258b50c82..65d9840d5 100644 --- a/app/models/custom_emoji.rb +++ b/app/models/custom_emoji.rb @@ -13,6 +13,8 @@ # created_at :datetime not null # updated_at :datetime not null # disabled :boolean default(FALSE), not null +# uri :string +# image_remote_url :string # class CustomEmoji < ApplicationRecord @@ -37,6 +39,10 @@ class CustomEmoji < ApplicationRecord domain.nil? end + def object_type + :emoji + end + class << self def from_text(text, domain) return [] if text.blank? diff --git a/app/serializers/activitypub/actor_serializer.rb b/app/serializers/activitypub/actor_serializer.rb index a11178f5b..896d67115 100644 --- a/app/serializers/activitypub/actor_serializer.rb +++ b/app/serializers/activitypub/actor_serializer.rb @@ -10,20 +10,6 @@ class ActivityPub::ActorSerializer < ActiveModel::Serializer has_one :public_key, serializer: ActivityPub::PublicKeySerializer - class ImageSerializer < ActiveModel::Serializer - include RoutingHelper - - attributes :type, :url - - def type - 'Image' - end - - def url - full_asset_url(object.url(:original)) - end - end - class EndpointsSerializer < ActiveModel::Serializer include RoutingHelper @@ -36,8 +22,8 @@ class ActivityPub::ActorSerializer < ActiveModel::Serializer has_one :endpoints, serializer: EndpointsSerializer - has_one :icon, serializer: ImageSerializer, if: :avatar_exists? - has_one :image, serializer: ImageSerializer, if: :header_exists? + has_one :icon, serializer: ActivityPub::ImageSerializer, if: :avatar_exists? + has_one :image, serializer: ActivityPub::ImageSerializer, if: :header_exists? def id account_url(object) diff --git a/app/serializers/activitypub/emoji_serializer.rb b/app/serializers/activitypub/emoji_serializer.rb new file mode 100644 index 000000000..7b06b1e5d --- /dev/null +++ b/app/serializers/activitypub/emoji_serializer.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +class ActivityPub::EmojiSerializer < ActiveModel::Serializer + include RoutingHelper + + attributes :id, :type, :name, :updated + + has_one :icon, serializer: ActivityPub::ImageSerializer + + def id + ActivityPub::TagManager.instance.uri_for(object) + end + + def type + 'Emoji' + end + + def icon + object.image + end + + def updated + object.updated_at.iso8601 + end + + def name + ":#{object.shortcode}:" + end +end diff --git a/app/serializers/activitypub/image_serializer.rb b/app/serializers/activitypub/image_serializer.rb new file mode 100644 index 000000000..a015c6b1b --- /dev/null +++ b/app/serializers/activitypub/image_serializer.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +class ActivityPub::ImageSerializer < ActiveModel::Serializer + include RoutingHelper + + attributes :type, :media_type, :url + + def type + 'Image' + end + + def url + full_asset_url(object.url(:original)) + end + + def media_type + object.content_type + end +end diff --git a/app/serializers/activitypub/note_serializer.rb b/app/serializers/activitypub/note_serializer.rb index 4dbf6a444..24c39f3c9 100644 --- a/app/serializers/activitypub/note_serializer.rb +++ b/app/serializers/activitypub/note_serializer.rb @@ -142,21 +142,6 @@ class ActivityPub::NoteSerializer < ActiveModel::Serializer end end - class CustomEmojiSerializer < ActiveModel::Serializer - include RoutingHelper - - attributes :type, :href, :name - - def type - 'Emoji' - end - - def href - full_asset_url(object.image.url) - end - - def name - ":#{object.shortcode}:" - end + class CustomEmojiSerializer < ActivityPub::EmojiSerializer end end diff --git a/config/routes.rb b/config/routes.rb index cc1f66e52..bd7068b5c 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -96,8 +96,9 @@ Rails.application.routes.draw do resources :sessions, only: [:destroy] end - resources :media, only: [:show] - resources :tags, only: [:show] + resources :media, only: [:show] + resources :tags, only: [:show] + resources :emojis, only: [:show] get '/media_proxy/:id/(*any)', to: 'media_proxy#show', as: :media_proxy diff --git a/db/migrate/20171006142024_add_uri_to_custom_emojis.rb b/db/migrate/20171006142024_add_uri_to_custom_emojis.rb new file mode 100644 index 000000000..04dfcf397 --- /dev/null +++ b/db/migrate/20171006142024_add_uri_to_custom_emojis.rb @@ -0,0 +1,6 @@ +class AddUriToCustomEmojis < ActiveRecord::Migration[5.1] + def change + add_column :custom_emojis, :uri, :string + add_column :custom_emojis, :image_remote_url, :string + end +end diff --git a/db/schema.rb b/db/schema.rb index 3358e2997..7180d3515 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20171005171936) do +ActiveRecord::Schema.define(version: 20171006142024) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -99,6 +99,8 @@ ActiveRecord::Schema.define(version: 20171005171936) do t.datetime "created_at", null: false t.datetime "updated_at", null: false t.boolean "disabled", default: false, null: false + t.string "uri" + t.string "image_remote_url" t.index ["shortcode", "domain"], name: "index_custom_emojis_on_shortcode_and_domain", unique: true end diff --git a/spec/lib/activitypub/activity/create_spec.rb b/spec/lib/activitypub/activity/create_spec.rb index cdd499150..3c3991c13 100644 --- a/spec/lib/activitypub/activity/create_spec.rb +++ b/spec/lib/activitypub/activity/create_spec.rb @@ -290,7 +290,9 @@ RSpec.describe ActivityPub::Activity::Create do tag: [ { type: 'Emoji', - href: 'http://example.com/emoji.png', + icon: { + url: 'http://example.com/emoji.png', + }, name: 'tinking', }, ], @@ -314,7 +316,9 @@ RSpec.describe ActivityPub::Activity::Create do tag: [ { type: 'Emoji', - href: 'http://example.com/emoji.png', + icon: { + url: 'http://example.com/emoji.png', + }, }, ], } @@ -326,7 +330,7 @@ RSpec.describe ActivityPub::Activity::Create do end end - context 'with emojis missing href' do + context 'with emojis missing icon' do let(:object_json) do { id: 'bar', -- cgit From 633426b2616e8559acfa76f4294a51afcf434fc2 Mon Sep 17 00:00:00 2001 From: nullkal Date: Sun, 8 Oct 2017 03:26:43 +0900 Subject: Add moderation note (#5240) * Add moderation note * Add frozen_string_literal * Make rspec pass --- .../admin/account_moderation_notes_controller.rb | 31 ++++++++++++++++++++++ app/controllers/admin/accounts_controller.rb | 5 +++- .../admin/account_moderation_notes_helper.rb | 4 +++ app/models/account.rb | 4 +++ app/models/account_moderation_note.rb | 22 +++++++++++++++ .../_account_moderation_note.html.haml | 10 +++++++ app/views/admin/accounts/show.html.haml | 22 +++++++++++++++ config/locales/en.yml | 10 +++++++ config/routes.rb | 2 ++ ...171005102658_create_account_moderation_notes.rb | 12 +++++++++ db/schema.rb | 11 ++++++++ .../account_moderation_notes_controller_spec.rb | 4 +++ .../account_moderation_note_fabricator.rb | 4 +++ .../admin/account_moderation_notes_helper_spec.rb | 15 +++++++++++ spec/models/account_moderation_note_spec.rb | 5 ++++ 15 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 app/controllers/admin/account_moderation_notes_controller.rb create mode 100644 app/helpers/admin/account_moderation_notes_helper.rb create mode 100644 app/models/account_moderation_note.rb create mode 100644 app/views/admin/account_moderation_notes/_account_moderation_note.html.haml create mode 100644 db/migrate/20171005102658_create_account_moderation_notes.rb create mode 100644 spec/controllers/admin/account_moderation_notes_controller_spec.rb create mode 100644 spec/fabricators/account_moderation_note_fabricator.rb create mode 100644 spec/helpers/admin/account_moderation_notes_helper_spec.rb create mode 100644 spec/models/account_moderation_note_spec.rb (limited to 'db') diff --git a/app/controllers/admin/account_moderation_notes_controller.rb b/app/controllers/admin/account_moderation_notes_controller.rb new file mode 100644 index 000000000..414a875d0 --- /dev/null +++ b/app/controllers/admin/account_moderation_notes_controller.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +class Admin::AccountModerationNotesController < Admin::BaseController + def create + @account_moderation_note = current_account.account_moderation_notes.new(resource_params) + if @account_moderation_note.save + @target_account = @account_moderation_note.target_account + redirect_to admin_account_path(@target_account.id), notice: I18n.t('admin.account_moderation_notes.created_msg') + else + @account = @account_moderation_note.target_account + @moderation_notes = @account.targeted_moderation_notes.latest + render template: 'admin/accounts/show' + end + end + + def destroy + @account_moderation_note = AccountModerationNote.find(params[:id]) + @target_account = @account_moderation_note.target_account + @account_moderation_note.destroy + redirect_to admin_account_path(@target_account.id), notice: I18n.t('admin.account_moderation_notes.destroyed_msg') + end + + private + + def resource_params + params.require(:account_moderation_note).permit( + :content, + :target_account_id + ) + end +end diff --git a/app/controllers/admin/accounts_controller.rb b/app/controllers/admin/accounts_controller.rb index 54c659e1b..ffa4dc850 100644 --- a/app/controllers/admin/accounts_controller.rb +++ b/app/controllers/admin/accounts_controller.rb @@ -9,7 +9,10 @@ module Admin @accounts = filtered_accounts.page(params[:page]) end - def show; end + def show + @account_moderation_note = current_account.account_moderation_notes.new(target_account: @account) + @moderation_notes = @account.targeted_moderation_notes.latest + end def subscribe Pubsubhubbub::SubscribeWorker.perform_async(@account.id) diff --git a/app/helpers/admin/account_moderation_notes_helper.rb b/app/helpers/admin/account_moderation_notes_helper.rb new file mode 100644 index 000000000..b17c52264 --- /dev/null +++ b/app/helpers/admin/account_moderation_notes_helper.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +module Admin::AccountModerationNotesHelper +end diff --git a/app/models/account.rb b/app/models/account.rb index 54035d94a..88f16026d 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -90,6 +90,10 @@ class Account < ApplicationRecord has_many :reports has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id + # Moderation notes + has_many :account_moderation_notes + has_many :targeted_moderation_notes, class_name: 'AccountModerationNote', foreign_key: :target_account_id + scope :remote, -> { where.not(domain: nil) } scope :local, -> { where(domain: nil) } scope :without_followers, -> { where(followers_count: 0) } diff --git a/app/models/account_moderation_note.rb b/app/models/account_moderation_note.rb new file mode 100644 index 000000000..be52d10b6 --- /dev/null +++ b/app/models/account_moderation_note.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +# == Schema Information +# +# Table name: account_moderation_notes +# +# id :integer not null, primary key +# content :text not null +# account_id :integer +# target_account_id :integer +# created_at :datetime not null +# updated_at :datetime not null +# + +class AccountModerationNote < ApplicationRecord + belongs_to :account + belongs_to :target_account, class_name: 'Account' + + scope :latest, -> { reorder('created_at DESC') } + + validates :content, presence: true, length: { maximum: 500 } +end diff --git a/app/views/admin/account_moderation_notes/_account_moderation_note.html.haml b/app/views/admin/account_moderation_notes/_account_moderation_note.html.haml new file mode 100644 index 000000000..4651630e9 --- /dev/null +++ b/app/views/admin/account_moderation_notes/_account_moderation_note.html.haml @@ -0,0 +1,10 @@ +%tr + %td + = simple_format(h(account_moderation_note.content)) + %td + = account_moderation_note.account.acct + %td + %time.formatted{ datetime: account_moderation_note.created_at.iso8601, title: l(account_moderation_note.created_at) } + = l account_moderation_note.created_at + %td + = link_to t('admin.account_moderation_notes.delete'), admin_account_moderation_note_path(account_moderation_note), method: :delete diff --git a/app/views/admin/accounts/show.html.haml b/app/views/admin/accounts/show.html.haml index 3775b6721..1f5c8fcf5 100644 --- a/app/views/admin/accounts/show.html.haml +++ b/app/views/admin/accounts/show.html.haml @@ -129,3 +129,25 @@ %tr %th= t('admin.accounts.followers_url') %td= link_to @account.followers_url, @account.followers_url + +%hr +%h3= t('admin.accounts.moderation_notes') + += simple_form_for @account_moderation_note, url: admin_account_moderation_notes_path do |f| + = render 'shared/error_messages', object: @account_moderation_note + + = f.input :content + = f.hidden_field :target_account_id + + .actions + = f.button :button, t('admin.account_moderation_notes.create'), type: :submit + +.table-wrapper + %table.table + %thead + %tr + %th + %th= t('admin.account_moderation_notes.account') + %th= t('admin.account_moderation_notes.created_at') + %tbody + = render @moderation_notes diff --git a/config/locales/en.yml b/config/locales/en.yml index 82041be24..7d2596fc6 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -76,6 +76,7 @@ en: silenced: Silenced suspended: Suspended title: Moderation + moderation_notes: Moderation notes most_recent_activity: Most recent activity most_recent_ip: Most recent IP not_subscribed: Not subscribed @@ -109,6 +110,15 @@ en: unsubscribe: Unsubscribe username: Username web: Web + + account_moderation_notes: + account: Moderator + created_at: Date + create: Create + created_msg: Moderation note successfully created! + delete: Delete + destroyed_msg: Moderation note successfully destroyed! + custom_emojis: copied_msg: Successfully created local copy of the emoji copy: Copy diff --git a/config/routes.rb b/config/routes.rb index bd7068b5c..5a6351f77 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -147,6 +147,8 @@ Rails.application.routes.draw do post :disable end end + + resources :account_moderation_notes, only: [:create, :destroy] end get '/admin', to: redirect('/admin/settings/edit', status: 302) diff --git a/db/migrate/20171005102658_create_account_moderation_notes.rb b/db/migrate/20171005102658_create_account_moderation_notes.rb new file mode 100644 index 000000000..d1802b5b3 --- /dev/null +++ b/db/migrate/20171005102658_create_account_moderation_notes.rb @@ -0,0 +1,12 @@ +class CreateAccountModerationNotes < ActiveRecord::Migration[5.1] + def change + create_table :account_moderation_notes do |t| + t.text :content, null: false + t.references :account + t.references :target_account + + t.timestamps + end + add_foreign_key :account_moderation_notes, :accounts, column: :target_account_id + end +end diff --git a/db/schema.rb b/db/schema.rb index 7180d3515..91f1b1acb 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -23,6 +23,16 @@ ActiveRecord::Schema.define(version: 20171006142024) do t.index ["account_id", "domain"], name: "index_account_domain_blocks_on_account_id_and_domain", unique: true end + create_table "account_moderation_notes", force: :cascade do |t| + t.text "content", null: false + t.bigint "account_id" + t.bigint "target_account_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["account_id"], name: "index_account_moderation_notes_on_account_id" + t.index ["target_account_id"], name: "index_account_moderation_notes_on_target_account_id" + end + create_table "accounts", force: :cascade do |t| t.string "username", default: "", null: false t.string "domain" @@ -449,6 +459,7 @@ ActiveRecord::Schema.define(version: 20171006142024) do end add_foreign_key "account_domain_blocks", "accounts", name: "fk_206c6029bd", on_delete: :cascade + add_foreign_key "account_moderation_notes", "accounts", column: "target_account_id" add_foreign_key "blocks", "accounts", column: "target_account_id", name: "fk_9571bfabc1", on_delete: :cascade add_foreign_key "blocks", "accounts", name: "fk_4269e03e65", on_delete: :cascade add_foreign_key "conversation_mutes", "accounts", name: "fk_225b4212bb", on_delete: :cascade diff --git a/spec/controllers/admin/account_moderation_notes_controller_spec.rb b/spec/controllers/admin/account_moderation_notes_controller_spec.rb new file mode 100644 index 000000000..ca4e55c4d --- /dev/null +++ b/spec/controllers/admin/account_moderation_notes_controller_spec.rb @@ -0,0 +1,4 @@ +require 'rails_helper' + +RSpec.describe Admin::AccountModerationNotesController, type: :controller do +end diff --git a/spec/fabricators/account_moderation_note_fabricator.rb b/spec/fabricators/account_moderation_note_fabricator.rb new file mode 100644 index 000000000..9277af165 --- /dev/null +++ b/spec/fabricators/account_moderation_note_fabricator.rb @@ -0,0 +1,4 @@ +Fabricator(:account_moderation_note) do + content "MyText" + account nil +end diff --git a/spec/helpers/admin/account_moderation_notes_helper_spec.rb b/spec/helpers/admin/account_moderation_notes_helper_spec.rb new file mode 100644 index 000000000..01b60c851 --- /dev/null +++ b/spec/helpers/admin/account_moderation_notes_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the Admin::AccountModerationNotesHelper. For example: +# +# describe Admin::AccountModerationNotesHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe Admin::AccountModerationNotesHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/account_moderation_note_spec.rb b/spec/models/account_moderation_note_spec.rb new file mode 100644 index 000000000..c4be8c4af --- /dev/null +++ b/spec/models/account_moderation_note_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe AccountModerationNote, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end -- cgit From 6c54d2e5837de941457371e9afffd05606d88180 Mon Sep 17 00:00:00 2001 From: nullkal Date: Tue, 10 Oct 2017 20:12:17 +0900 Subject: foreign_key, non-nullable, dependent: destroy in account_moderation_notes (#5294) * Add foreign key constraint to column `account` in `account_moderation_notes` * Change account_id and target_account_id to non-nullable in account_moderation_notes * Add dependent: :destroy to account and target_account in account_moderation_notes --- app/models/account.rb | 4 ++-- app/models/account_moderation_note.rb | 5 ++--- .../20171010023049_add_foreign_key_to_account_moderation_notes.rb | 5 +++++ ...5614_change_accounts_nonnullable_in_account_moderation_notes.rb | 6 ++++++ db/schema.rb | 7 ++++--- 5 files changed, 19 insertions(+), 8 deletions(-) create mode 100644 db/migrate/20171010023049_add_foreign_key_to_account_moderation_notes.rb create mode 100644 db/migrate/20171010025614_change_accounts_nonnullable_in_account_moderation_notes.rb (limited to 'db') diff --git a/app/models/account.rb b/app/models/account.rb index 88f16026d..3dc2a95ab 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -91,8 +91,8 @@ class Account < ApplicationRecord has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id # Moderation notes - has_many :account_moderation_notes - has_many :targeted_moderation_notes, class_name: 'AccountModerationNote', foreign_key: :target_account_id + has_many :account_moderation_notes, dependent: :destroy + has_many :targeted_moderation_notes, class_name: 'AccountModerationNote', foreign_key: :target_account_id, dependent: :destroy scope :remote, -> { where.not(domain: nil) } scope :local, -> { where(domain: nil) } diff --git a/app/models/account_moderation_note.rb b/app/models/account_moderation_note.rb index be52d10b6..3ac9b1ac1 100644 --- a/app/models/account_moderation_note.rb +++ b/app/models/account_moderation_note.rb @@ -1,13 +1,12 @@ # frozen_string_literal: true - # == Schema Information # # Table name: account_moderation_notes # # id :integer not null, primary key # content :text not null -# account_id :integer -# target_account_id :integer +# account_id :integer not null +# target_account_id :integer not null # created_at :datetime not null # updated_at :datetime not null # diff --git a/db/migrate/20171010023049_add_foreign_key_to_account_moderation_notes.rb b/db/migrate/20171010023049_add_foreign_key_to_account_moderation_notes.rb new file mode 100644 index 000000000..fc1e1ab91 --- /dev/null +++ b/db/migrate/20171010023049_add_foreign_key_to_account_moderation_notes.rb @@ -0,0 +1,5 @@ +class AddForeignKeyToAccountModerationNotes < ActiveRecord::Migration[5.1] + def change + add_foreign_key :account_moderation_notes, :accounts + end +end diff --git a/db/migrate/20171010025614_change_accounts_nonnullable_in_account_moderation_notes.rb b/db/migrate/20171010025614_change_accounts_nonnullable_in_account_moderation_notes.rb new file mode 100644 index 000000000..747e5a826 --- /dev/null +++ b/db/migrate/20171010025614_change_accounts_nonnullable_in_account_moderation_notes.rb @@ -0,0 +1,6 @@ +class ChangeAccountsNonnullableInAccountModerationNotes < ActiveRecord::Migration[5.1] + def change + change_column_null :account_moderation_notes, :account_id, false + change_column_null :account_moderation_notes, :target_account_id, false + end +end diff --git a/db/schema.rb b/db/schema.rb index 91f1b1acb..f9722ccda 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20171006142024) do +ActiveRecord::Schema.define(version: 20171010025614) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -25,8 +25,8 @@ ActiveRecord::Schema.define(version: 20171006142024) do create_table "account_moderation_notes", force: :cascade do |t| t.text "content", null: false - t.bigint "account_id" - t.bigint "target_account_id" + t.bigint "account_id", null: false + t.bigint "target_account_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["account_id"], name: "index_account_moderation_notes_on_account_id" @@ -459,6 +459,7 @@ ActiveRecord::Schema.define(version: 20171006142024) do end add_foreign_key "account_domain_blocks", "accounts", name: "fk_206c6029bd", on_delete: :cascade + add_foreign_key "account_moderation_notes", "accounts" add_foreign_key "account_moderation_notes", "accounts", column: "target_account_id" add_foreign_key "blocks", "accounts", column: "target_account_id", name: "fk_9571bfabc1", on_delete: :cascade add_foreign_key "blocks", "accounts", name: "fk_4269e03e65", on_delete: :cascade -- cgit