active_storage_dedup 1.0.0.alpha
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/.rubocop.yml +8 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +419 -0
- data/Rakefile +12 -0
- data/lib/active_storage_dedup/attachment_extension.rb +39 -0
- data/lib/active_storage_dedup/attachment_options.rb +21 -0
- data/lib/active_storage_dedup/blob_deduplication.rb +139 -0
- data/lib/active_storage_dedup/changes_extension.rb +70 -0
- data/lib/active_storage_dedup/configuration.rb +78 -0
- data/lib/active_storage_dedup/deduplication_job.rb +100 -0
- data/lib/active_storage_dedup/railtie.rb +48 -0
- data/lib/active_storage_dedup/version.rb +5 -0
- data/lib/active_storage_dedup.rb +16 -0
- data/lib/generators/active_storage_dedup/install_generator.rb +36 -0
- data/lib/generators/active_storage_dedup/templates/README +44 -0
- data/lib/generators/active_storage_dedup/templates/add_active_storage_dedup.rb.erb +41 -0
- data/lib/generators/active_storage_dedup/templates/initializer.rb +42 -0
- data/lib/tasks/active_storage_dedup.rake +101 -0
- data/sig/active_storage_dedup.rbs +4 -0
- metadata +164 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: a4f96450774fa2234c8f821d1444e709da77e1ddc506c5f2df6a303fad7576a4
|
|
4
|
+
data.tar.gz: a50c1171305466705117062c7cafaafac2433e73f6e3c3fdee7115f4268bdeff
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: f00a16a468856689d0d6d9ad111c84b4377b6d66fbefda0f8505aa494116b2054c02c1c3caf1fb16db28ddfc28285313ab76844fe48ec72743fe8af9833cdf3a
|
|
7
|
+
data.tar.gz: 81bbc60a6bb8df0f1e8b4fbc0921fb98242a41a47aeb69d7207f4521712a1e79377c0f5fca8466a4b75d5aba7fbf6ecee4f14eaa411ac4b975d95b87713dbfc6
|
data/.rspec
ADDED
data/.rubocop.yml
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
|
2
|
+
|
|
3
|
+
## Our Pledge
|
|
4
|
+
|
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
|
10
|
+
identity and orientation.
|
|
11
|
+
|
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
13
|
+
diverse, inclusive, and healthy community.
|
|
14
|
+
|
|
15
|
+
## Our Standards
|
|
16
|
+
|
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
|
18
|
+
community include:
|
|
19
|
+
|
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
|
24
|
+
and learning from the experience
|
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
|
26
|
+
community
|
|
27
|
+
|
|
28
|
+
Examples of unacceptable behavior include:
|
|
29
|
+
|
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
|
31
|
+
any kind
|
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
33
|
+
* Public or private harassment
|
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
|
35
|
+
without their explicit permission
|
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
|
37
|
+
professional setting
|
|
38
|
+
|
|
39
|
+
## Enforcement Responsibilities
|
|
40
|
+
|
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
44
|
+
or harmful.
|
|
45
|
+
|
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
49
|
+
decisions when appropriate.
|
|
50
|
+
|
|
51
|
+
## Scope
|
|
52
|
+
|
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
|
54
|
+
an individual is officially representing the community in public spaces.
|
|
55
|
+
Examples of representing our community include using an official email address,
|
|
56
|
+
posting via an official social media account, or acting as an appointed
|
|
57
|
+
representative at an online or offline event.
|
|
58
|
+
|
|
59
|
+
## Enforcement
|
|
60
|
+
|
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
62
|
+
reported to the community leaders responsible for enforcement at
|
|
63
|
+
[INSERT CONTACT METHOD].
|
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
|
65
|
+
|
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
|
67
|
+
reporter of any incident.
|
|
68
|
+
|
|
69
|
+
## Enforcement Guidelines
|
|
70
|
+
|
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
|
73
|
+
|
|
74
|
+
### 1. Correction
|
|
75
|
+
|
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
77
|
+
unprofessional or unwelcome in the community.
|
|
78
|
+
|
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
|
82
|
+
|
|
83
|
+
### 2. Warning
|
|
84
|
+
|
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
|
86
|
+
actions.
|
|
87
|
+
|
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
|
93
|
+
ban.
|
|
94
|
+
|
|
95
|
+
### 3. Temporary Ban
|
|
96
|
+
|
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
|
98
|
+
sustained inappropriate behavior.
|
|
99
|
+
|
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
|
101
|
+
communication with the community for a specified period of time. No public or
|
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
|
104
|
+
Violating these terms may lead to a permanent ban.
|
|
105
|
+
|
|
106
|
+
### 4. Permanent Ban
|
|
107
|
+
|
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
|
111
|
+
|
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
|
113
|
+
community.
|
|
114
|
+
|
|
115
|
+
## Attribution
|
|
116
|
+
|
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
118
|
+
version 2.1, available at
|
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
|
120
|
+
|
|
121
|
+
Community Impact Guidelines were inspired by
|
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
|
123
|
+
|
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
|
127
|
+
|
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Harisankar P S aka coderhs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
# ActiveStorageDedup
|
|
2
|
+
|
|
3
|
+
Automatic deduplication for Rails Active Storage. Prevents duplicate file uploads by reusing existing blobs with matching checksums, saving storage space and bandwidth.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Automatic Deduplication**: Reuses existing blobs when identical files are uploaded
|
|
8
|
+
- **All Upload Methods Supported**: Works with form uploads, direct uploads, and programmatic attachments
|
|
9
|
+
- **Service-Aware**: Properly handles multiple storage services (local, S3, etc.)
|
|
10
|
+
- **Reference Counting**: Tracks blob usage with automatic counter cache
|
|
11
|
+
- **Three-Level Configuration**: Master switch, global default, and per-attachment control
|
|
12
|
+
- **Sanity Check Job**: Periodic job to clean up any duplicates that slip through
|
|
13
|
+
- **Auto-Purge Orphans**: Automatically removes blobs when no attachments reference them
|
|
14
|
+
- **Zero Dependencies**: Works with standard Rails Active Storage
|
|
15
|
+
|
|
16
|
+
## Demo/Implementation APP
|
|
17
|
+
|
|
18
|
+
[Github Repo](https://github.com/coderhs/rails-storage-example)
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
Add this line to your application's Gemfile:
|
|
23
|
+
|
|
24
|
+
```ruby
|
|
25
|
+
gem 'active_storage_dedup'
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Then execute:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
bundle install
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Run the install generator to create the migration:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
rails generate active_storage_dedup:install
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
This will:
|
|
41
|
+
- Create the migration to add `reference_count` column to `active_storage_blobs`
|
|
42
|
+
- Create composite index on `[checksum, service_name]` for fast duplicate lookups
|
|
43
|
+
- Create an initializer at `config/initializers/active_storage_dedup.rb` with default configuration
|
|
44
|
+
|
|
45
|
+
Finally, run the migration:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
rails db:migrate
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
### Basic Setup
|
|
54
|
+
|
|
55
|
+
ActiveStorageDedup works automatically with all Active Storage attachments. No code changes required!
|
|
56
|
+
|
|
57
|
+
```ruby
|
|
58
|
+
class User < ApplicationRecord
|
|
59
|
+
has_one_attached :avatar
|
|
60
|
+
has_many_attached :documents
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Upload a file
|
|
64
|
+
user.avatar.attach(io: File.open('photo.jpg'), filename: 'photo.jpg')
|
|
65
|
+
|
|
66
|
+
# Upload the same file to another user - reuses existing blob!
|
|
67
|
+
another_user.avatar.attach(io: File.open('photo.jpg'), filename: 'photo.jpg')
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Configuration
|
|
71
|
+
|
|
72
|
+
The install generator creates `config/initializers/active_storage_dedup.rb` with these options:
|
|
73
|
+
|
|
74
|
+
```ruby
|
|
75
|
+
ActiveStorageDedup.configure do |config|
|
|
76
|
+
# Master switch to enable/disable the entire gem (default: true)
|
|
77
|
+
# Set to false to completely disable all deduplication and lifecycle management
|
|
78
|
+
config.enabled = true
|
|
79
|
+
|
|
80
|
+
# Default deduplication setting for all attachments (default: true)
|
|
81
|
+
# Controls whether attachments deduplicate by default when gem is enabled
|
|
82
|
+
# Can be overridden per-attachment
|
|
83
|
+
config.deduplicate_by_default = true
|
|
84
|
+
|
|
85
|
+
# Auto-purge blobs when reference_count reaches 0 (default: true)
|
|
86
|
+
config.auto_purge_orphans = true
|
|
87
|
+
end
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Three-Level Control
|
|
91
|
+
|
|
92
|
+
#### Level 1: Master Switch (`enabled`)
|
|
93
|
+
Completely enable or disable the gem:
|
|
94
|
+
|
|
95
|
+
```ruby
|
|
96
|
+
config.enabled = false # Gem does nothing - Active Storage works normally
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
#### Level 2: Global Default (`deduplicate_by_default`)
|
|
100
|
+
Set the default behavior for all attachments:
|
|
101
|
+
|
|
102
|
+
```ruby
|
|
103
|
+
# Opt-out pattern: deduplicate by default, disable selectively
|
|
104
|
+
config.enabled = true
|
|
105
|
+
config.deduplicate_by_default = true
|
|
106
|
+
|
|
107
|
+
class Product < ApplicationRecord
|
|
108
|
+
has_many_attached :images # ✅ Deduplicates
|
|
109
|
+
has_one_attached :badge, deduplicate: false # ❌ Doesn't deduplicate
|
|
110
|
+
end
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
# Opt-in pattern: don't deduplicate by default, enable selectively
|
|
115
|
+
config.enabled = true
|
|
116
|
+
config.deduplicate_by_default = false
|
|
117
|
+
|
|
118
|
+
class Product < ApplicationRecord
|
|
119
|
+
has_many_attached :images, deduplicate: true # ✅ Deduplicates
|
|
120
|
+
has_one_attached :avatar # ❌ Doesn't deduplicate
|
|
121
|
+
end
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
#### Level 3: Per-Attachment Override
|
|
125
|
+
Override the global default for specific attachments:
|
|
126
|
+
|
|
127
|
+
```ruby
|
|
128
|
+
class Product < ApplicationRecord
|
|
129
|
+
# Uses config.deduplicate_by_default
|
|
130
|
+
has_one_attached :image
|
|
131
|
+
|
|
132
|
+
# Explicit override: always deduplicate
|
|
133
|
+
has_many_attached :photos, deduplicate: true
|
|
134
|
+
|
|
135
|
+
# Explicit override: never deduplicate
|
|
136
|
+
has_one_attached :unique_badge, deduplicate: false
|
|
137
|
+
end
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Rake Tasks
|
|
141
|
+
|
|
142
|
+
#### Report Duplicates
|
|
143
|
+
|
|
144
|
+
See all duplicate blobs (dry run):
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
rails active_storage_dedup:report_duplicates
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Output:
|
|
151
|
+
```
|
|
152
|
+
Checksum: abc123def456...
|
|
153
|
+
Service: local
|
|
154
|
+
Filename: photo.jpg
|
|
155
|
+
Total blobs: 3
|
|
156
|
+
Keeper blob ID: 42 (1 attachments)
|
|
157
|
+
Duplicate blob IDs: 43, 44
|
|
158
|
+
Total attachments across duplicates: 2
|
|
159
|
+
Wasted storage: 2.5 MB
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
#### Clean Up All Duplicates
|
|
163
|
+
|
|
164
|
+
Run the sanity check job to find and merge all duplicate blobs:
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
rails active_storage_dedup:cleanup_all
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Or run the job directly:
|
|
171
|
+
|
|
172
|
+
```ruby
|
|
173
|
+
ActiveStorageDedup::DeduplicationJob.perform_now
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
#### Backfill Reference Counts
|
|
177
|
+
|
|
178
|
+
Recalculate reference counts for existing blobs:
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
rails active_storage_dedup:backfill_reference_count
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### Scheduled Cleanup (Recommended)
|
|
185
|
+
|
|
186
|
+
Due to race conditions during concurrent uploads, duplicates may occasionally slip through. Run the sanity check job periodically to clean them up:
|
|
187
|
+
|
|
188
|
+
**With whenever gem:**
|
|
189
|
+
|
|
190
|
+
```ruby
|
|
191
|
+
# config/schedule.rb
|
|
192
|
+
every 1.week, at: '2:00 am' do
|
|
193
|
+
runner "ActiveStorageDedup::DeduplicationJob.perform_later"
|
|
194
|
+
end
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
**With sidekiq-cron:**
|
|
198
|
+
|
|
199
|
+
```ruby
|
|
200
|
+
# config/initializers/sidekiq.rb
|
|
201
|
+
Sidekiq::Cron::Job.create(
|
|
202
|
+
name: 'Active Storage Dedup - weekly cleanup',
|
|
203
|
+
cron: '0 2 * * 0', # 2 AM every Sunday
|
|
204
|
+
class: 'ActiveStorageDedup::DeduplicationJob'
|
|
205
|
+
)
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
**With Rails built-in scheduler (Good Job, Solid Queue, etc.):**
|
|
209
|
+
|
|
210
|
+
```ruby
|
|
211
|
+
# config/recurring.yml
|
|
212
|
+
active_storage_dedup_cleanup:
|
|
213
|
+
class: ActiveStorageDedup::DeduplicationJob
|
|
214
|
+
schedule: "weekly on sunday at 2am"
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
**With cron:**
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
# Weekly cleanup every Sunday at 2 AM
|
|
221
|
+
0 2 * * 0 cd /app && bin/rails runner "ActiveStorageDedup::DeduplicationJob.perform_now"
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
## How It Works
|
|
225
|
+
|
|
226
|
+
### Deduplication Strategy
|
|
227
|
+
|
|
228
|
+
ActiveStorageDedup uses `[checksum, service_name]` as the deduplication key:
|
|
229
|
+
|
|
230
|
+
- **Checksum**: Active Storage's built-in MD5 checksum
|
|
231
|
+
- **Service Name**: Storage service (local, S3, etc.)
|
|
232
|
+
|
|
233
|
+
When a file is uploaded:
|
|
234
|
+
|
|
235
|
+
1. Checksum is calculated
|
|
236
|
+
2. Existing blob with same checksum + service is searched
|
|
237
|
+
3. If found, existing blob is reused
|
|
238
|
+
4. If not found, new blob is created
|
|
239
|
+
|
|
240
|
+
### Three Interception Points
|
|
241
|
+
|
|
242
|
+
The gem patches three Active Storage methods to cover all upload flows:
|
|
243
|
+
|
|
244
|
+
1. **`build_after_unfurling`**: Form uploads (Rails 6.1+)
|
|
245
|
+
2. **`create_before_direct_upload!`**: Direct uploads to cloud storage
|
|
246
|
+
3. **`create_after_unfurling!`**: Programmatic attachments via `attach()`
|
|
247
|
+
|
|
248
|
+
### Reference Counting
|
|
249
|
+
|
|
250
|
+
Uses Rails' built-in counter cache:
|
|
251
|
+
|
|
252
|
+
```ruby
|
|
253
|
+
# Automatically incremented when attachment created
|
|
254
|
+
belongs_to :blob, counter_cache: :reference_count
|
|
255
|
+
|
|
256
|
+
# Check references
|
|
257
|
+
blob.reference_count # => 3
|
|
258
|
+
blob.attachments.count # => 3
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
### Auto-Purge Orphans
|
|
262
|
+
|
|
263
|
+
When an attachment is destroyed:
|
|
264
|
+
|
|
265
|
+
1. Counter cache automatically decrements
|
|
266
|
+
2. If `reference_count` reaches 0, blob is purged
|
|
267
|
+
3. Physical file is deleted from storage
|
|
268
|
+
|
|
269
|
+
## Advanced Usage
|
|
270
|
+
|
|
271
|
+
### Direct Uploads
|
|
272
|
+
|
|
273
|
+
Works seamlessly with Active Storage's direct upload feature:
|
|
274
|
+
|
|
275
|
+
```javascript
|
|
276
|
+
// Client-side - no changes needed!
|
|
277
|
+
// ActiveStorageDedup automatically deduplicates on the server
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
### Multiple Services
|
|
281
|
+
|
|
282
|
+
Blobs are service-specific. Same file on different services = separate blobs:
|
|
283
|
+
|
|
284
|
+
```ruby
|
|
285
|
+
user.avatar.attach(
|
|
286
|
+
io: File.open('photo.jpg'),
|
|
287
|
+
filename: 'photo.jpg',
|
|
288
|
+
service_name: :local # Uses local storage
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
user.documents.attach(
|
|
292
|
+
io: File.open('photo.jpg'),
|
|
293
|
+
filename: 'photo.jpg',
|
|
294
|
+
service_name: :amazon # Creates separate blob on S3
|
|
295
|
+
)
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
### Manual Sanity Check
|
|
299
|
+
|
|
300
|
+
Run the sanity check job manually to clean up all duplicates:
|
|
301
|
+
|
|
302
|
+
```ruby
|
|
303
|
+
# Run synchronously (blocks until complete)
|
|
304
|
+
ActiveStorageDedup::DeduplicationJob.perform_now
|
|
305
|
+
|
|
306
|
+
# Run asynchronously (queues the job)
|
|
307
|
+
ActiveStorageDedup::DeduplicationJob.perform_later
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
The job will:
|
|
311
|
+
1. Scan the database for all duplicate blob groups (same checksum + service)
|
|
312
|
+
2. For each group, keep the oldest blob and merge duplicates into it
|
|
313
|
+
3. Move all attachments from duplicate blobs to the keeper
|
|
314
|
+
4. Update reference counts
|
|
315
|
+
5. Delete duplicate blob records
|
|
316
|
+
|
|
317
|
+
## Examples
|
|
318
|
+
|
|
319
|
+
### Reference Counting
|
|
320
|
+
|
|
321
|
+
```ruby
|
|
322
|
+
blob = ActiveStorage::Blob.create_after_upload!(
|
|
323
|
+
io: File.open('shared.jpg'),
|
|
324
|
+
filename: 'shared.jpg'
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
user1.avatar.attach(blob)
|
|
328
|
+
blob.reference_count # => 1
|
|
329
|
+
|
|
330
|
+
user2.avatar.attach(blob)
|
|
331
|
+
blob.reference_count # => 2
|
|
332
|
+
|
|
333
|
+
user1.avatar.purge
|
|
334
|
+
blob.reference_count # => 1
|
|
335
|
+
|
|
336
|
+
user2.avatar.purge
|
|
337
|
+
# => Blob automatically purged (reference_count = 0)
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
### Environment-Specific Configuration
|
|
341
|
+
|
|
342
|
+
```ruby
|
|
343
|
+
# config/environments/development.rb
|
|
344
|
+
Rails.application.configure do
|
|
345
|
+
# Disable in development for faster uploads during testing
|
|
346
|
+
ActiveStorageDedup.configure do |config|
|
|
347
|
+
config.enabled = false
|
|
348
|
+
end
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
# config/environments/production.rb
|
|
352
|
+
Rails.application.configure do
|
|
353
|
+
# Enable in production to save storage
|
|
354
|
+
ActiveStorageDedup.configure do |config|
|
|
355
|
+
config.enabled = true
|
|
356
|
+
config.deduplicate_by_default = true
|
|
357
|
+
end
|
|
358
|
+
end
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
## Quick Reference
|
|
362
|
+
|
|
363
|
+
### Configuration Options
|
|
364
|
+
|
|
365
|
+
| Option | Default | Description |
|
|
366
|
+
|--------|---------|-------------|
|
|
367
|
+
| `enabled` | `true` | Master switch - disables entire gem when false |
|
|
368
|
+
| `deduplicate_by_default` | `true` | Default behavior for attachments (can be overridden) |
|
|
369
|
+
| `auto_purge_orphans` | `true` | Automatically delete blobs when reference_count = 0 |
|
|
370
|
+
|
|
371
|
+
### Model Options
|
|
372
|
+
|
|
373
|
+
```ruby
|
|
374
|
+
has_one_attached :avatar # Uses deduplicate_by_default
|
|
375
|
+
has_many_attached :docs, deduplicate: true # Always deduplicate
|
|
376
|
+
has_one_attached :badge, deduplicate: false # Never deduplicate
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
### Rake Tasks
|
|
380
|
+
|
|
381
|
+
| Task | Description |
|
|
382
|
+
|------|-------------|
|
|
383
|
+
| `rails active_storage_dedup:report_duplicates` | Show all duplicate blobs (dry run) |
|
|
384
|
+
| `rails active_storage_dedup:cleanup_all` | Run sanity check to merge duplicates |
|
|
385
|
+
| `rails active_storage_dedup:backfill_reference_count` | Recalculate reference counts |
|
|
386
|
+
|
|
387
|
+
### Jobs
|
|
388
|
+
|
|
389
|
+
```ruby
|
|
390
|
+
# Run sanity check manually
|
|
391
|
+
ActiveStorageDedup::DeduplicationJob.perform_now
|
|
392
|
+
|
|
393
|
+
# Queue sanity check
|
|
394
|
+
ActiveStorageDedup::DeduplicationJob.perform_later
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
## Requirements
|
|
398
|
+
|
|
399
|
+
- Rails 6.0+
|
|
400
|
+
- Active Storage configured
|
|
401
|
+
- ActiveJob (for background cleanup)
|
|
402
|
+
|
|
403
|
+
## Development
|
|
404
|
+
|
|
405
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
|
406
|
+
|
|
407
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
|
408
|
+
|
|
409
|
+
## Contributing
|
|
410
|
+
|
|
411
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/coderhs/active_storage_dedup. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/coderhs/active_storage_dedup/blob/main/CODE_OF_CONDUCT.md).
|
|
412
|
+
|
|
413
|
+
## License
|
|
414
|
+
|
|
415
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
|
416
|
+
|
|
417
|
+
## Code of Conduct
|
|
418
|
+
|
|
419
|
+
Everyone interacting in the ActiveStorageDedup project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/coderhs/active_storage_dedup/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveStorageDedup
|
|
4
|
+
module AttachmentExtension
|
|
5
|
+
extend ActiveSupport::Concern
|
|
6
|
+
|
|
7
|
+
included do
|
|
8
|
+
belongs_to :blob, class_name: "ActiveStorage::Blob",
|
|
9
|
+
counter_cache: :reference_count,
|
|
10
|
+
optional: false
|
|
11
|
+
|
|
12
|
+
after_destroy :purge_orphaned_blob, if: :should_manage_lifecycle?
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
private
|
|
16
|
+
|
|
17
|
+
def purge_orphaned_blob
|
|
18
|
+
return unless ActiveStorageDedup.configuration.auto_purge_orphans
|
|
19
|
+
return unless blob.present?
|
|
20
|
+
|
|
21
|
+
Rails.logger.debug "[ActiveStorageDedup] Checking if blob #{blob.id} should be purged (attachment destroyed)"
|
|
22
|
+
|
|
23
|
+
blob.reload
|
|
24
|
+
Rails.logger.debug "[ActiveStorageDedup] Blob #{blob.id} reference_count: #{blob.reference_count}"
|
|
25
|
+
|
|
26
|
+
if blob.reference_count <= 0
|
|
27
|
+
Rails.logger.info "[ActiveStorageDedup] ♻ Purging orphaned blob #{blob.id} (reference_count: #{blob.reference_count})"
|
|
28
|
+
blob.purge
|
|
29
|
+
else
|
|
30
|
+
Rails.logger.debug "[ActiveStorageDedup] Keeping blob #{blob.id} (still has #{blob.reference_count} reference(s))"
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def should_manage_lifecycle?
|
|
35
|
+
ActiveStorageDedup.configuration.auto_purge_orphans &&
|
|
36
|
+
ActiveStorageDedup.deduplicate_enabled_for?(record, name)
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveStorageDedup
|
|
4
|
+
module AttachmentOptions
|
|
5
|
+
def has_one_attached(name, dependent: :purge_later, service: nil,
|
|
6
|
+
strict_loading: false, deduplicate: true, **options)
|
|
7
|
+
ActiveStorageDedup.register_attachment(self.name, name, deduplicate: deduplicate)
|
|
8
|
+
|
|
9
|
+
super(name, dependent: dependent, service: service,
|
|
10
|
+
strict_loading: strict_loading, **options)
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def has_many_attached(name, dependent: :purge_later, service: nil,
|
|
14
|
+
strict_loading: false, deduplicate: true, **options)
|
|
15
|
+
ActiveStorageDedup.register_attachment(self.name, name, deduplicate: deduplicate)
|
|
16
|
+
|
|
17
|
+
super(name, dependent: dependent, service: service,
|
|
18
|
+
strict_loading: strict_loading, **options)
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|