dynamic_links 0.1.0 → 0.3.0

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.
Files changed (30) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -0
  3. data/MIT-LICENSE +21 -0
  4. data/README.md +239 -5
  5. data/app/controllers/dynamic_links/application_controller.rb +17 -1
  6. data/app/controllers/dynamic_links/redirects_controller.rb +29 -0
  7. data/app/controllers/dynamic_links/v1/short_links_controller.rb +93 -12
  8. data/app/jobs/dynamic_links/generate_short_links_job.rb +1 -1
  9. data/app/jobs/dynamic_links/shorten_url_job.rb +31 -0
  10. data/app/models/dynamic_links/client.rb +5 -0
  11. data/app/models/dynamic_links/shortened_url.rb +20 -2
  12. data/config/routes.rb +3 -0
  13. data/db/migrate/20231228165744_create_dynamic_links_clients.rb +8 -1
  14. data/db/migrate/20231228175142_create_dynamic_links_shortened_urls.rb +3 -4
  15. data/db/migrate/20240128030329_fix_citus_index.rb +34 -0
  16. data/db/migrate/20240128030419_add_unique_index_to_shortened_urls.rb +5 -0
  17. data/lib/dynamic_links/async/locker.rb +60 -0
  18. data/lib/dynamic_links/configuration.rb +95 -3
  19. data/lib/dynamic_links/error_classes.rb +6 -0
  20. data/lib/dynamic_links/logger.rb +32 -0
  21. data/lib/dynamic_links/redis_config.rb +22 -0
  22. data/lib/dynamic_links/shortener.rb +52 -0
  23. data/lib/dynamic_links/shortening_strategies/base_strategy.rb +6 -0
  24. data/lib/dynamic_links/shortening_strategies/nano_id_strategy.rb +7 -9
  25. data/lib/dynamic_links/shortening_strategies/redis_counter_strategy.rb +25 -14
  26. data/lib/dynamic_links/strategy_factory.rb +28 -1
  27. data/lib/dynamic_links/validator.rb +14 -0
  28. data/lib/dynamic_links/version.rb +1 -1
  29. data/lib/dynamic_links.rb +54 -17
  30. metadata +73 -16
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f8be4269ba92cfbec08c29ec6a6a871383b8470736057204fa24234ebfc70a98
4
- data.tar.gz: 90a2df3615def525638fc53eeb23eef0a367d0137993b6303630d7d868ac3443
3
+ metadata.gz: 191decc937ca3ca35b6911558962c6ecea550a22e8032c907f01d1098aced607
4
+ data.tar.gz: 6f983f6713bc399e51fb5990fa888e7a2165b21ed09ec00097d99ee92173ba7e
5
5
  SHA512:
6
- metadata.gz: 3ca6e9c92116542c9df6895e861843c03e951cb7e87bf567bc189b4811f8fb6cf95e097123b4569843ea18f8780289e1bec70b2de2a8bd92532f929277e0578e
7
- data.tar.gz: 50e65b566b1b36f9b169f0a7c35610720027f030c31d4fd7fe861ee077ea1b5c043391a51caf4f34c612f13456fdcf16cbb95d39a019c69f65bb2676bc2d7fd7
6
+ metadata.gz: 55a751b1dc66a5687d91e430888efd4f96f83ad6e227dca63a1e2c571958131640eae71b5524ebf50e4330c2f9bb6f803dfa28cf413f607aee23f682bd18ff6c
7
+ data.tar.gz: 261cc6051c78d7a736c560fbc5ffa14eac49c3f0b031a8f1f516b5bbd1fa181f5d26b391fe819c23ef05b6d1c77fe2ae49f7867bef5f7aaf86a2cf387135fa51
data/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.3.0] - 2025-07-25
8
+
9
+ - [#101](https://github.com/saiqulhaq/dynamic_links/pull/101)
10
+
11
+ - New Feature: Added `find_or_create` REST API endpoint that finds existing short links or creates new ones
12
+ - New Feature: Added `DynamicLinks.find_short_link` method to search for existing short links by URL and client
13
+ - Enhancement: Improved URL validation in REST API controllers with dedicated `valid_url?` method
14
+ - Enhancement: Code cleanup - removed unnecessary hash brackets in `find_by` calls
15
+
16
+ ## [0.2.0] - 2025-06-17
17
+
18
+ - [#88](https://github.com/saiqulhaq/dynamic_links/pull/88)
19
+
20
+ - New Feature: Added API method to expand shortened URLs via the `expand` endpoint
21
+ - New Feature: Added fallback mode to redirect to Firebase host when short URL not found
22
+ - Enhancement: Improved multi-tenant support in controllers
23
+
24
+ - [#19](https://github.com/saiqulhaq/dynamic_links/pull/19)
25
+
26
+ - New Feature: Added asynchronous URL shortening functionality, improving performance for large-scale operations.
27
+ - Refactor: Updated DynamicLinks::Configuration class to accommodate new features and improve flexibility.
28
+ - Test: Expanded test coverage to include new features and functionalities.
29
+ - Documentation: Updated README with instructions on performance optimization and running unit tests.
30
+ - Chore: Added benchmarking scripts to measure the performance of synchronous vs asynchronous URL shortening and different versions of `create_or_find` method.
31
+
32
+ - Custom domain per client
33
+ - Ruby API for URL shortening.
34
+ - Add CRC32, nanoid, Redis counter, and KGS strategies to shorten an URL.
35
+ - URL validation feature.
36
+ - Configuration option to enable/disable REST API.
37
+ - Redirection feature. [#14](https://github.com/saiqulhaq/dynamic_links/pull/14)
data/MIT-LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023-2025 Saiqul Haq
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 CHANGED
@@ -1,10 +1,14 @@
1
1
  # DynamicLinks
2
2
 
3
+ [![Unit Tests](https://github.com/saiqulhaq/dynamic_links/actions/workflows/unit_test.yml/badge.svg)](https://github.com/saiqulhaq/dynamic_links/actions/workflows/unit_test.yml)
4
+
3
5
  DynamicLinks is a flexible URL shortening Ruby gem, designed to provide various strategies for URL shortening, similar to Firebase Dynamic Links.
4
6
 
7
+ By default, encoding strategies such as MD5 will generate the same short URL for the same input URL. This behavior ensures consistency and prevents the creation of multiple records for identical URLs. For scenarios requiring unique short URLs for each request, strategies like RedisCounterStrategy can be used, which generate a new short URL every time, regardless of the input URL.
8
+
5
9
  ## Usage
6
10
 
7
- To use DynamicLinks, you need to configure the shortening strategy in an initializer or before you start shortening URLs.
11
+ To use DynamicLinks, you need to configure the shortening strategy and other settings in an initializer or before you start shortening URLs.
8
12
 
9
13
  ### Configuration
10
14
 
@@ -12,10 +16,70 @@ In your Rails initializer or similar setup code, configure DynamicLinks like thi
12
16
 
13
17
  ```ruby
14
18
  DynamicLinks.configure do |config|
15
- config.shortening_strategy = :MD5
19
+ config.shortening_strategy = :md5 # Default strategy
20
+ config.redis_config = { host: 'localhost', port: 6379 } # Redis configuration
21
+ config.redis_pool_size = 10 # Redis connection pool size
22
+ config.redis_pool_timeout = 3 # Redis connection pool timeout in seconds
23
+ config.enable_rest_api = true # Enable or disable REST API feature
24
+
25
+ # New configuration added in PR #88
26
+ config.enable_fallback_mode = false # When true, falls back to Firebase URL if a short link is not found
27
+ config.firebase_host = "https://example.app.goo.gl" # Firebase host URL for fallbacks
16
28
  end
17
29
  ```
18
30
 
31
+ ## Development Environment
32
+
33
+ This project supports two development environment options: GitHub Codespaces and local Docker Compose.
34
+
35
+ ### Option 1: GitHub Codespaces
36
+
37
+ This project is configured to work with GitHub development containers, providing a consistent development environment.
38
+
39
+ #### Opening in GitHub Codespaces
40
+
41
+ 1. Navigate to the GitHub repository
42
+ 2. Click the "Code" button
43
+ 3. Select the "Codespaces" tab
44
+ 4. Click "Create codespace on main"
45
+
46
+ #### Development in the Codespace
47
+
48
+ Once the development container is created and set up:
49
+
50
+ 1. The container includes Ruby 3.2, PostgreSQL, Redis, and other dependencies
51
+ 2. Run the test suite: `cd test/dummy && bin/rails test`
52
+ 3. Start the Rails server: `cd test/dummy && bin/rails server`
53
+
54
+ ### Option 2: Local Development with Docker Compose
55
+
56
+ For local development, we use Docker Compose with VS Code's Remote - Containers extension.
57
+
58
+ #### Prerequisites
59
+
60
+ 1. Install [Docker](https://docs.docker.com/get-docker/)
61
+ 2. Install [VS Code](https://code.visualstudio.com/)
62
+ 3. Install the [Remote - Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers)
63
+
64
+ #### Opening in VS Code with Containers
65
+
66
+ 1. Clone the repository to your local machine
67
+ 2. Open the project folder in VS Code
68
+ 3. VS Code will detect the devcontainer configuration and prompt you to reopen in a container
69
+ 4. Click "Reopen in Container"
70
+
71
+ #### Working with the Docker Compose Setup
72
+
73
+ - The setup includes three services: app (Ruby), postgres (PostgreSQL), and redis (Redis)
74
+ - Database and Redis connections are automatically configured
75
+ - Use VS Code tasks (F1 -> "Tasks: Run Task") for common operations like:
76
+ - Starting the Rails server
77
+ - Running tests
78
+ - Running the Rails console
79
+ - Managing Docker Compose services
80
+
81
+ For more details on the Docker Compose setup, refer to the [Docker Compose documentation](DOCKER_COMPOSE.md). 4. Access the application at the forwarded port (usually port 3000)
82
+
19
83
  ### Shortening a URL
20
84
 
21
85
  To shorten a URL, simply call:
@@ -24,6 +88,147 @@ To shorten a URL, simply call:
24
88
  shortened_url = DynamicLinks.shorten_url("https://example.com")
25
89
  ```
26
90
 
91
+ ### Finding an Existing Short Link
92
+
93
+ To find an existing short link for a URL:
94
+
95
+ ```ruby
96
+ short_link_data = DynamicLinks.find_short_link("https://example.com", client)
97
+ if short_link_data
98
+ puts short_link_data[:short_url] # e.g., "https://client.com/abc123"
99
+ puts short_link_data[:full_url] # e.g., "https://example.com"
100
+ else
101
+ puts "No existing short link found"
102
+ end
103
+ ```
104
+
105
+ ## REST API
106
+
107
+ DynamicLinks provides a REST API for URL shortening operations when `enable_rest_api` is set to `true` in the configuration.
108
+
109
+ ### Authentication
110
+
111
+ All API endpoints require an `api_key` parameter that corresponds to a registered client.
112
+
113
+ ### Endpoints
114
+
115
+ #### Create Short Link
116
+
117
+ Creates a new short link for a URL.
118
+
119
+ **Endpoint:** `POST /v1/shortLinks`
120
+
121
+ **Parameters:**
122
+
123
+ - `url` (required): The URL to shorten
124
+ - `api_key` (required): Client API key
125
+
126
+ **Example Request:**
127
+
128
+ ```bash
129
+ curl -X POST "http://localhost:3000/v1/shortLinks" \
130
+ -H "Content-Type: application/json" \
131
+ -d '{
132
+ "url": "https://example.com/long-url",
133
+ "api_key": "your-api-key"
134
+ }'
135
+ ```
136
+
137
+ **Example Response:**
138
+
139
+ ```json
140
+ {
141
+ "shortLink": "https://your-domain.com/abc123",
142
+ "previewLink": "https://your-domain.com/abc123?preview=true",
143
+ "warning": []
144
+ }
145
+ ```
146
+
147
+ #### Find or Create Short Link
148
+
149
+ Finds an existing short link for a URL, or creates a new one if none exists. This prevents duplicate short links for the same URL and client.
150
+
151
+ **Endpoint:** `POST /v1/shortLinks/findOrCreate`
152
+
153
+ **Parameters:**
154
+
155
+ - `url` (required): The URL to find or shorten
156
+ - `api_key` (required): Client API key
157
+
158
+ **Example Request:**
159
+
160
+ ```bash
161
+ curl -X POST "http://localhost:3000/v1/shortLinks/findOrCreate" \
162
+ -H "Content-Type: application/json" \
163
+ -d '{
164
+ "url": "https://example.com/long-url",
165
+ "api_key": "your-api-key"
166
+ }'
167
+ ```
168
+
169
+ **Example Response (existing link found):**
170
+
171
+ ```json
172
+ {
173
+ "shortLink": "https://your-domain.com/abc123",
174
+ "previewLink": "https://your-domain.com/abc123?preview=true",
175
+ "warning": []
176
+ }
177
+ ```
178
+
179
+ **Example Response (new link created):**
180
+
181
+ ```json
182
+ {
183
+ "shortLink": "https://your-domain.com/def456",
184
+ "previewLink": "https://your-domain.com/def456?preview=true",
185
+ "warning": []
186
+ }
187
+ ```
188
+
189
+ #### Expand Short Link
190
+
191
+ Retrieves the original URL from a short link.
192
+
193
+ **Endpoint:** `GET /v1/shortLinks/{short_url}`
194
+
195
+ **Parameters:**
196
+
197
+ - `short_url` (in URL): The short URL code to expand
198
+ - `api_key` (required): Client API key
199
+
200
+ **Example Request:**
201
+
202
+ ```bash
203
+ curl "http://localhost:3000/v1/shortLinks/abc123?api_key=your-api-key"
204
+ ```
205
+
206
+ **Example Response:**
207
+
208
+ ```json
209
+ {
210
+ "url": "https://example.com/long-url"
211
+ }
212
+ ```
213
+
214
+ ### Error Responses
215
+
216
+ The API returns appropriate HTTP status codes and error messages:
217
+
218
+ - `400 Bad Request`: Invalid URL format
219
+ - `401 Unauthorized`: Invalid or missing API key
220
+ - `403 Forbidden`: REST API feature is disabled
221
+ - `404 Not Found`: Short link not found (expand endpoint)
222
+ - `500 Internal Server Error`: Server error
223
+
224
+ **Example Error Response:**
225
+
226
+ ```json
227
+ {
228
+ "error": "Invalid URL"
229
+ }
230
+ ```
231
+
27
232
  ## Available Shortening Strategies
28
233
 
29
234
  DynamicLinks supports various shortening strategies. The default strategy is `MD5`, but you can choose among several others, including `NanoIdStrategy`, `RedisCounterStrategy`, `Sha256Strategy`, and more.
@@ -33,7 +238,7 @@ Depending on the strategy you choose, you may need to install additional depende
33
238
  ### Optional Dependencies
34
239
 
35
240
  - For `NanoIdStrategy`, add `gem 'nanoid', '~> 2.0'` to your Gemfile.
36
- - For `RedisCounterStrategy`, add `gem 'redis', '>= 4'` to your Gemfile.
241
+ - For `RedisCounterStrategy`, ensure Redis is available and configured. Redis strategy requires `connection_pool` gem too.
37
242
 
38
243
  Ensure you bundle these dependencies along with the DynamicLinks gem if you plan to use these strategies.
39
244
 
@@ -57,9 +262,38 @@ Or install it yourself as:
57
262
  $ gem install dynamic_links
58
263
  ```
59
264
 
60
- ## Contributing
265
+ ## Performance
266
+
267
+ Benchmarking scripts are available in the `benchmarks/` directory to measure performance:
268
+
269
+ - `ruby_api.rb`: Benchmarks Ruby API URL shortening performance
270
+ - `rest_api.py`: Benchmarks REST API URL shortening performance
271
+ - `create_or_find.rb`: Compares performance of different `create_or_find` methods
272
+
273
+ You can run these benchmarks to measure performance in your specific environment.
274
+
275
+ ## How to run the unit test
276
+
277
+ ### When using a Plain PostgreSQL DB
278
+
279
+ ```bash
280
+ rails db:setup
281
+ rails db:test:prepare
282
+ rails test
283
+ ```
284
+
285
+ ### When using PostgreSQL DB with Citus
286
+
287
+ ```bash
288
+ export CITUS_ENABLED=true
289
+ rails db:setup
290
+ rails db:test:prepare
291
+ rails test
292
+ ```
61
293
 
62
- We welcome contributions to DynamicLinks! Please read the contributing guidelines to get started.
294
+ Note:
295
+ Make sure the Citus extension already enabled on the installed PostgreSQL
296
+ We don't manage it on Rails.
63
297
 
64
298
  ## License
65
299
 
@@ -1,4 +1,20 @@
1
1
  module DynamicLinks
2
- class ApplicationController < ActionController::Base
2
+ class ApplicationController < ActionController::API
3
+ def multi_tenant(client, db_infra_strategy = DynamicLinks.configuration.db_infra_strategy)
4
+ if db_infra_strategy == :sharding
5
+ if defined?(::MultiTenant)
6
+ ::MultiTenant.with(client) do
7
+ yield
8
+ end
9
+ else
10
+ # Rails.logger.warn 'MultiTenant gem is not installed. Please install it to use sharding strategy'
11
+ DynamicLinks::Logger.log_warn('MultiTenant gem is not installed. Please install it to use sharding strategy')
12
+
13
+ yield
14
+ end
15
+ else
16
+ yield
17
+ end
18
+ end
3
19
  end
4
20
  end
@@ -0,0 +1,29 @@
1
+ module DynamicLinks
2
+ class RedirectsController < ApplicationController
3
+ def show
4
+ client = DynamicLinks::Client.find_by({ hostname: request.host })
5
+ unless client
6
+ render plain: 'URL not found', status: :not_found
7
+ return
8
+ end
9
+
10
+ multi_tenant(client) do
11
+ short_url = params[:short_url]
12
+ link = ShortenedUrl.find_by(short_url: short_url)
13
+
14
+ if link.nil?
15
+ if DynamicLinks.configuration.enable_fallback_mode && DynamicLinks.configuration.firebase_host.present?
16
+ redirect_to "#{DynamicLinks.configuration.firebase_host}/#{short_url}", status: :found, allow_other_host: true
17
+ else
18
+ render plain: 'Not found', status: :not_found
19
+ end
20
+ return
21
+ end
22
+
23
+ raise ActiveRecord::RecordNotFound if link.expired?
24
+
25
+ redirect_to link.url, status: :found, allow_other_host: true
26
+ end
27
+ end
28
+ end
29
+ end
@@ -1,14 +1,95 @@
1
- class DynamicLinks::V1::ShortLinksController < ApplicationController
2
- def create
3
- url = params.require(:url)
4
- # validate url
5
- # if !url_shortener.valid_url?(url)
6
- # render json: { error: 'invalid url' }, status: :bad_request
7
- # return
8
- # end
9
-
10
- # shorten url
11
- # save to db (not implemented yet)
12
- render json: DynamicLinks.generate_short_url(url), status: :created
1
+ module DynamicLinks
2
+ class V1::ShortLinksController < ApplicationController
3
+ before_action :check_rest_api_enabled
4
+
5
+ def create
6
+ url = params.require(:url)
7
+ client = DynamicLinks::Client.find_by(api_key: params.require(:api_key))
8
+
9
+ unless client
10
+ render json: { error: 'Invalid API key' }, status: :unauthorized
11
+ return
12
+ end
13
+
14
+ multi_tenant(client) do
15
+ render json: DynamicLinks.generate_short_url(url, client), status: :created
16
+ end
17
+ rescue DynamicLinks::InvalidURIError
18
+ render json: { error: 'Invalid URL' }, status: :bad_request
19
+ rescue => e
20
+ DynamicLinks::Logger.log_error(e)
21
+ render json: { error: 'An error occurred while processing your request' }, status: :internal_server_error
22
+ end
23
+
24
+ def expand
25
+ api_key = params.require(:api_key)
26
+ client = DynamicLinks::Client.find_by(api_key: api_key)
27
+
28
+ unless client
29
+ render json: { error: 'Invalid API key' }, status: :unauthorized
30
+ return
31
+ end
32
+
33
+ multi_tenant(client) do
34
+ short_link = params.require(:short_url)
35
+ full_url = DynamicLinks.resolve_short_url(short_link)
36
+
37
+ if full_url
38
+ render json: { full_url: full_url }, status: :ok
39
+ else
40
+ render json: { error: 'Short link not found' }, status: :not_found
41
+ end
42
+ end
43
+ rescue => e
44
+ DynamicLinks::Logger.log_error(e)
45
+ render json: { error: 'An error occurred while processing your request' }, status: :internal_server_error
46
+ end
47
+
48
+ def find_or_create
49
+ url = params.require(:url)
50
+ client = DynamicLinks::Client.find_by(api_key: params.require(:api_key))
51
+
52
+ unless client
53
+ render json: { error: 'Invalid API key' }, status: :unauthorized
54
+ return
55
+ end
56
+
57
+ unless valid_url?(url)
58
+ render json: { error: 'Invalid URL' }, status: :bad_request
59
+ return
60
+ end
61
+
62
+ multi_tenant(client) do
63
+ short_link = DynamicLinks.find_short_link(url, client)
64
+
65
+ if short_link
66
+ render json: {
67
+ shortLink: short_link[:short_url],
68
+ previewLink: "#{short_link[:short_url]}?preview=true",
69
+ warning: []
70
+ }, status: :ok
71
+ else
72
+ render json: DynamicLinks.generate_short_url(url, client), status: :created
73
+ end
74
+ end
75
+ rescue => e
76
+ DynamicLinks::Logger.log_error(e)
77
+ render json: { error: 'An error occurred while processing your request' }, status: :internal_server_error
78
+ end
79
+
80
+ private
81
+
82
+ def check_rest_api_enabled
83
+ unless DynamicLinks.configuration.enable_rest_api
84
+ render json: { error: 'REST API feature is disabled' }, status: :forbidden
85
+ end
86
+ end
87
+
88
+ def valid_url?(url)
89
+ uri = URI.parse(url)
90
+ uri.is_a?(URI::HTTP) && uri.host.present? && uri.scheme.present?
91
+ rescue URI::InvalidURIError
92
+ false
93
+ end
13
94
  end
14
95
  end
@@ -1,5 +1,5 @@
1
1
  module DynamicLinks
2
- # This job generates short links in the background
2
+ # This job generates short links in the background for KGS strategy
3
3
  # It is intended to be run periodically
4
4
  # We can find available short links by querying the database with query:
5
5
  # ShortenedUrl.where(available: true)
@@ -0,0 +1,31 @@
1
+ module DynamicLinks
2
+ # @author Saiqul Haq <saiqulhaq@gmail.com>
3
+ # This job is used to create a shortened url
4
+ class ShortenUrlJob < ApplicationJob
5
+ queue_as :default
6
+
7
+ def perform(client, url, short_url, lock_key)
8
+ locker = DynamicLinks::Async::Locker.new
9
+ strategy = StrategyFactory.get_strategy(DynamicLinks.configuration.shortening_strategy)
10
+
11
+ begin
12
+ if strategy.always_growing?
13
+ storage.create!(client: client, url: url, short_url: short_url)
14
+ else
15
+ storage.find_or_create!(client, short_url, url)
16
+ end
17
+ locker.unlock(lock_key)
18
+ DynamicLinks::Logger.log_info("Lock key #{lock_key} deleted after ShortenUrlJob")
19
+ rescue => e
20
+ DynamicLinks::Logger.log_error("Error in ShortenUrlJob: #{e.message}")
21
+ raise e
22
+ end
23
+ end
24
+
25
+ private
26
+
27
+ def storage
28
+ @storage ||= ShortenedUrl
29
+ end
30
+ end
31
+ end
@@ -15,7 +15,12 @@
15
15
  #
16
16
  module DynamicLinks
17
17
  class Client < ApplicationRecord
18
+ VALID_SCHEMES = ['http', 'https'].freeze
19
+
18
20
  validates :name, presence: true, uniqueness: true
19
21
  validates :api_key, presence: true, uniqueness: true
22
+ validates :hostname, presence: true, uniqueness: true
23
+ validates :scheme, presence: true, inclusion: { in: VALID_SCHEMES }
24
+ validates :hostname, format: { with: /\A[a-z0-9]([a-z0-9\-]{,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9\-]{,61}[a-z0-9])?)*\z/i, message: 'must be a valid hostname' }
20
25
  end
21
26
  end
@@ -17,9 +17,27 @@
17
17
  #
18
18
  module DynamicLinks
19
19
  class ShortenedUrl < ApplicationRecord
20
- belongs_to :client, optional: true
20
+ belongs_to :client
21
+ multi_tenant :client if respond_to?(:multi_tenant)
21
22
 
22
23
  validates :url, presence: true
23
- validates :short_url, presence: true, uniqueness: true
24
+ validates :short_url, presence: true, uniqueness: { scope: :client_id }
25
+
26
+ def self.find_or_create!(client, short_url, url)
27
+ transaction do
28
+ record = find_or_create_by!(client: client, short_url: short_url) do |record|
29
+ record.url = url
30
+ end
31
+ record
32
+ end
33
+ rescue ActiveRecord::RecordInvalid => e
34
+ # Log the error and re-raise if needed or return a meaningful error message
35
+ DynamicLinks::Logger.log_error("ShortenedUrl creation failed: #{e.message}")
36
+ raise e
37
+ end
38
+
39
+ def expired?
40
+ expires_at&.past?
41
+ end
24
42
  end
25
43
  end
data/config/routes.rb CHANGED
@@ -2,7 +2,10 @@
2
2
  #
3
3
 
4
4
  DynamicLinks::Engine.routes.draw do
5
+ get '/:short_url', to: 'redirects#show', as: :shortened
5
6
  namespace :v1 do
6
7
  post "/shortLinks", to: "short_links#create", as: :short_links
8
+ post "/shortLinks/findOrCreate", to: "short_links#find_or_create", as: :find_or_create_short_link
9
+ get "/shortLinks/:short_url", to: "short_links#expand", as: :expand_short_link
7
10
  end
8
11
  end
@@ -3,11 +3,18 @@ class CreateDynamicLinksClients < ActiveRecord::Migration[7.1]
3
3
  create_table :dynamic_links_clients do |t|
4
4
  t.string :name, null: false
5
5
  t.string :api_key, null: false
6
+ t.string :scheme, default: 'https', null: false
7
+ t.string :hostname, null: false
6
8
 
7
9
  t.timestamps
8
10
  end
9
11
 
10
- add_index :dynamic_links_clients, :name, unique: true
12
+ if DynamicLinks.configuration.db_infra_strategy == :sharding
13
+ create_reference_table(:dynamic_links_clients)
14
+ end
15
+
16
+ add_index :dynamic_links_clients, :name
11
17
  add_index :dynamic_links_clients, :api_key, unique: true
18
+ add_index :dynamic_links_clients, :hostname, unique: true
12
19
  end
13
20
  end
@@ -7,15 +7,14 @@ class CreateDynamicLinksShortenedUrls < ActiveRecord::Migration[7.1]
7
7
  t.bigint :id, primary_key: true
8
8
  end
9
9
 
10
- t.references :client, null: true, foreign_key: { to_table: :dynamic_links_clients }, type: :bigint
10
+ t.references :client, foreign_key: { to_table: :dynamic_links_clients }, type: :bigint
11
+
11
12
  # 2083 is the maximum length of a URL according to the RFC 2616
12
13
  t.string :url, null: false, limit: 2083
13
14
  # 12 is the maximum length of a short URL if we use the RedisCounterStrategy
14
- t.string :short_url, null: false, limit: DynamicLinks::ShorteningStrategies::RedisCounterStrategy::MAX_LENGTH
15
+ t.string :short_url, null: false, limit: 20
15
16
  t.datetime :expires_at
16
17
  t.timestamps
17
18
  end
18
-
19
- add_index :dynamic_links_shortened_urls, :short_url, unique: true
20
19
  end
21
20
  end