make_id 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 90cbe0cbac923318d4badd6c848042404633a27c6fbecdd7e2509aee6c31ab5c
4
+ data.tar.gz: 41f946d9367bb73257ac31ffce792bd309f2e707c44b39003d66dcc3d1890a49
5
+ SHA512:
6
+ metadata.gz: da8822e1194eb4ed1e51f1090f120db17cdd421fc330f84dbe4b4556c1dd71eac4dc33dff678768999cee03ad21749a9f3bbb5a2949ced4f83c7f7afd802128a
7
+ data.tar.gz: '038ae0b3bc50252cd75eec5fb7283feb27381e3362bd2681fbba6ff225865727ef4fa560f84d24e8c4703f5ba96ce168c9278462b9469b97323ab981869e387d'
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.0
@@ -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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Allen Fair
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Allen Fair
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,167 @@
1
+ # MakeId
2
+
3
+ MakeID is a ruby library containing data record identifier generators. Perhaps it is a library of _identifier patterns_?
4
+ Let me know (by pull request) if you have any useful standard (or should be) id types.
5
+
6
+ Most databases use a sequential, auto-incrementing number as the primary key. For example, in PostgreSQL this is implemented using sequences.
7
+
8
+ Not every data "id" wants to use sequential numbers. These can be easy to guess and allow inpection of random records by altering the URL.
9
+
10
+ ## Installation
11
+
12
+ This is a gem, and is installed as such:
13
+
14
+ gem install make_id
15
+
16
+ or by placing in your Gemfile, or running this bundler command:
17
+
18
+ bundle add make_id
19
+
20
+ Alternatively, you can skip the dependency and "adopt" the primary file within this repo, `lib/make_id.rb`,
21
+ keeping the attribution comments to find upstream documentation, fixes, and new features.
22
+
23
+ Another good alternative to using sequential id's is an alternate or external id used for URL's. This external
24
+ id can be generated id of any of these schemes, along with a unique index on the column. This gives you the ease
25
+ of a standard sequential id, with the security of a randomly-generated identifier.
26
+
27
+ When storing a string key in the database, look at using fixed-size columns instead of "characer varying" strings
28
+ as these have an additional cost of storing the length (PostgreSQL uses 4 bytes). Also, consider index performance
29
+ as these id's will likely require a unique index.
30
+
31
+ ## Usage
32
+
33
+ Sequential Id's are great, and perform well in most cases. Here are a few alternatives to find here.
34
+
35
+ ### Base conversions and Check Digits
36
+
37
+ Larger numbers can be represented more compactly with a larger base or radix. MakeId has utilities to
38
+ convert to and from its supported bases. You can leverage these for URL Id's to avoid long or simple
39
+ numeric codes.
40
+
41
+ Bases supported are:
42
+
43
+ - Base62: digits, upper, and lower-case letters. No special characters
44
+ - Base32: digits and upper case without ambiguous characters "1lI" or "oO0"
45
+ - Base 2 through 36 (except 32): Ruby's `Integer#to_s(base)` is used
46
+ - Base64: Uses the `Base64.urlsafe_encode64` such has 2 special characters.
47
+ - Base63: It is not implemented.
48
+
49
+ The Base32 may seem out of place, but is useful for alpha-numeric codes the users are required to type, such as redemption codes.
50
+ All letter are folded to upper-case, and ambiguous characters are converted to the canonical ones.
51
+
52
+ MakeId.int_to_base(123456789, 32) #=> "3nqk8n"
53
+ MakeId.from_base("3nqk8n", 10) #=> 123456789
54
+ MakeId.int_to_base(123456789, 32) #=> "3nqk8n"
55
+ MakeId.verify_base32_id("...") #=> corrected_id or nil if error
56
+
57
+ ### Random Integer
58
+
59
+ MakeId can return a random (8-byte by default) integer. You can request it returned in a supported base,
60
+ and with an optional check_digit.
61
+ Usually, you would use the integer returned, and call `int_to_base` to format for a URL or code.
62
+
63
+ MakeId.random_id() #=> 15379918763975837985ZZ
64
+ MakeId.random_id(base: 62, check_digit: true) #=> "2984biEwRT1"
65
+
66
+ ### UUID
67
+
68
+ UUID are 16-byte numbers, usually represented in hexadecimal of the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`.
69
+ There are different schemes for UUID types, and each has it's use. Most record Id's use a randomly generated UUID,
70
+ which if very unlikely (but possible) to have collitions with existing keys. The `uuid_to_base` helper method
71
+ can be used to transform a long UUID into a possibly more palettable base representation.
72
+
73
+ u = MakeId.uuid #=> "1601125f-ee7c-4c0b-b693-dd2265edbcfc"
74
+ MakeId.uuid_to_base(u, 10) #=> 29248580887982686871727313613986053372 (38 characters)
75
+ MakeId.uuid_to_base(u, 62) #=> "fWJtuXEQJnkjxroWjkmei" (21 characters)
76
+
77
+ Note that some databases support a UUID type which makes storing UUID's easier, and since they are stored as a binary
78
+ field, consume less space.ZZ
79
+
80
+ ### Nano Id
81
+
82
+ Nano Id's are shorter unique strings generated from random characters, usually as a friendlier alternative
83
+ to UUID's. They also can be of any size, depending on the key range you require. Pay attention to the keyspace,
84
+ ensuring you have enough characters to avoid predictable collisions in the future.
85
+
86
+ MakeId.nano_id(size: 16) #=> "iZnLn96FVcjivEJA"
87
+ MakeId.nano_id(size: 16, base: 32) #=> "sf8kqb8ekn7k98rq"
88
+
89
+ A `request_id` is a nano_id that can be used to track requests and jobs. It is a 16-byte string, the same
90
+ storage as a UUID, but with columnar values. The substring of 3 for 8 is a short (8 character) version that
91
+ can be used as well, is easier to read, sortable within a day, and unique enough to work with.
92
+
93
+ id = MakeId.request_id #=> "494f1272t01000c4"
94
+ #-------------------------->YMDHsssuuqqwwrrr
95
+ id[3,8] #=> "f1272t01"
96
+ #-------------------------->Hsssuuqq
97
+
98
+ ### Snowflake Id
99
+
100
+ Snowflakes were invented at Twitter to stamp an identifier for a tweet or direct message.
101
+ It is an 8-byte integer intended to be time-sorted and unique across the fleet of servers saving messages.
102
+ It is a bit-mapped integer consisting of these parts:
103
+
104
+ - "Application Epoch" milliseconds (number of seconds since the designated start). positive sign and 41 bits.
105
+ - "Worker Id", a number from 0..1023 (10 bits) used to designate the datacenter, server, and/or process generating the id.
106
+ - "Sequence Id", a number from 0..4095 (12 bits) of messages within the given millisecond, or a random number within.
107
+
108
+ The application epoch is the start time before data was generated. This is set by passing a year integer or Time object.
109
+ The default is 2020 for the library. Because there are only 41 bits for the `time * 1000` (milliseconds),
110
+ higher order bits are removed. Therefore, limit the size of your epoch to a later date to keep the id's sortable as well as readable.
111
+
112
+ MakeId.epoch = 2020 # or Time.utc(2020)
113
+ MakeId.snowflake_id => 618906575771271168
114
+ #--------------------->eeeeeeeeeeuuussrrr (Bit breakdown for understanding, not to scale)
115
+
116
+ The `worker_id` defaults to 0 and can be set with the APP_WORKER_ID environment variable or call
117
+ to a setter at the startup of the application. Set with a number appropriate for your environment.
118
+
119
+ You can also pass in options to return it as a different base, and with a check digit.
120
+
121
+ MakeId.app_worker_id = 234
122
+ MakeId.snowflake_id => 618905333721374720
123
+ MakeId.snowflake_id(worker_id: 12, base: 32, sequence_method: :random) #=> "2tmxk6ne81jd5"
124
+
125
+ The `snowflake_uuid` method provides a time-based identifier, great for sorting just as sequential numbers, but unique enough to fit the bill.
126
+
127
+ MakeId.snowflake_uuid # w> "66d735c6-0be2-6517-da69-57d440987c18"
128
+ u = MakeId.snowflake_uuid #=> "66d735e6-7ac4-8bfc-5af0-39b4e2c96b05"
129
+ #------------------------->eeeeeeee-uuuw-wwrr-rrrr-rrrrrrrrrrrr
130
+
131
+ Want a ISO-like readable timestamp in your UUID? The `snowflake_datetime_uuid` method combines elements of the
132
+ snowflake id (below) and the human-readable ISO timestamp in the UUID. Also includes milliseconds,
133
+ the "worker id" for the snowflake id, and a randomized 12-byte field. This could be useful for time-series
134
+ records or when you need a slowflake ID but have a UUID column to fill.
135
+
136
+ MakeID.snowflake_datetime_uuid #=> "20240904-1418-5332-2000-3a38e61d5582"
137
+ #------------------------>YYYYMMDD-hhmm-ssuu-uwww-rrrrrrrrrrrr
138
+
139
+ ## Experimental Id's
140
+
141
+ The `event_id` is a string, sortable by creation time, with visible time seperator columns.
142
+ It is of the format "YMDhmsuurrrr", using Base62, with an optional check_sum characer.
143
+ It also used the application epoch described under `snowflake_id`. "uu" represents the fractional
144
+ seconds that can be represented in Base62, and a 4-character random Base64 "nano_id".
145
+
146
+ MakeId.epoch = 2020
147
+ MakeId.event_id #=> "493KgpQGErTB"
148
+ #------------------->YMDhmsuurrrr ()
149
+ MakeId.event_id(check_digit: true) #=> "493Kkha6HZa2" (3 random chars + check digit)
150
+
151
+ ## Development
152
+
153
+ 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.
154
+
155
+ 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).
156
+
157
+ ## Contributing
158
+
159
+ Bug reports and pull requests are welcome on GitHub at https://github.com/afair/make_id. 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/afair/make_id/blob/main/CODE_OF_CONDUCT.md).
160
+
161
+ ## License
162
+
163
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
164
+
165
+ ## Code of Conduct
166
+
167
+ Everyone interacting in the MakeId project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/afair/make_id/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]
11
+
12
+ desc "Open and IRB Console with the gem loaded"
13
+ task :console do
14
+ sh "bundle exec irb -Ilib -I . -r make_id"
15
+ end
data/bin/make-id ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Usage: make-id
5
+ # Description: Prints a unique id. Useful for batch scripting?
6
+ require 'rubygems'
7
+ require 'make_id'
8
+ # In development mode, do: bundle exec bin/make-id
9
+
10
+ # For now, print set of Id's
11
+
12
+ # UUID: Print random UUID, UUID converted to base 10, UUID converted to base 32, UUID converted to base 62
13
+ id = MakeId.uuid
14
+ int = MakeId.uuid_to_base(id)
15
+ puts "UUID: \t#{id}\t#{int}\t#{MakeId.int_to_base(int,32)}\t#{MakeId.int_to_base(int,62)}"
16
+
17
+ # DateTimeUUId: Print DateTime UUID, DateTime UUID converted to base 10, DateTime UUID converted to base 32, DateTime UUID converted to base 62
18
+ id = MakeId.datetime_uuid
19
+ int = MakeId.uuid_to_base(id)
20
+ puts "DateTimeUUId:\t#{id}\t#{int}\t#{MakeId.int_to_base(int,32)}\t#{MakeId.int_to_base(int,62)}"
21
+
22
+ # EpochUUID: Print DateTime UUID, DateTime UUID converted to base 10, DateTime UUID converted to base 32, DateTime UUID converted to base 62
23
+ id = MakeId.epoch_uuid
24
+ int = MakeId.uuid_to_base(id)
25
+ puts "EpochUUID:\t#{id}\t#{int}\t#{MakeId.int_to_base(int,32)}\t#{MakeId.int_to_base(int,62)}"
26
+ id = MakeId.epoch_uuid(application_epoch: true)
27
+ int = MakeId.uuid_to_base(id)
28
+ puts "AppEpochUUID:\t#{id}\t#{int}\t#{MakeId.int_to_base(int,32)}\t#{MakeId.int_to_base(int,62)}"
29
+
30
+ # RandomId: Print random Id, Random Id converted to base 10, Random Id converted to base 32, Random Id converted to base 62
31
+ id = MakeId.random_id
32
+ puts "RandomId:\t#{id}\t#{MakeId.int_to_base(id,32)}\t#{MakeId.int_to_base(id,62)}"
33
+
34
+ # SnowflakeId: Print Snowflake Id, Snowflake Id converted to base 10, Snowflake Id converted to base 32, Snowflake Id converted to base 62
35
+ id = MakeId.snowflake_id
36
+ puts "SnowflakeId:\t#{id}\t#{MakeId.int_to_base(id,32)}\t#{MakeId.int_to_base(id,62)}"
37
+
38
+ # NanoId: Print Nano Id
39
+ id = MakeId.nano_id
40
+ int = MakeId.base_to_int(id, 62)
41
+ puts "NanoId: \t#{id}\t#{MakeId.int_to_base(int,32)}\t#{int}"
42
+
43
+ # EventId: Print Event Id
44
+ id = MakeId.event_id
45
+ int = MakeId.base_to_int(id, 62)
46
+ puts "EventId:\t#{id}\t\t#{MakeId.int_to_base(int,32)}\t#{int}"
47
+
48
+ # RequesetId: Print it
49
+ id = MakeId.request_id
50
+ puts "RequestId:\t#{id}\t\t#{id[3,8]}"
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MakeId
4
+ VERSION = "0.1.0"
5
+ end
data/lib/make_id.rb ADDED
@@ -0,0 +1,362 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "make_id/version"
4
+ require "securerandom"
5
+ require "base64"
6
+ require "zlib"
7
+
8
+ # MakeID generates record Identifiers other than sequential integers.
9
+ # MakeId - From the "make_id" gem found at https://github.com/afair/make_id
10
+ # License - MIT, see the LICENSE file in the gem's source code.
11
+ # Adopt - Copy this file to your application with the above attribution to
12
+ # allow others to find fixes, documentation, and new features.
13
+ module MakeId
14
+ # class Error < StandardError; end
15
+
16
+ CHARS32 = "0123456789abcdefghjkmnpqrstvwxyz" # Avoiding ambiguous 0/o i/l/I
17
+ CHARS62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
18
+ EPOCH_TWITTER = Time.utc(2006, 3, 21, 20, 50, 14)
19
+
20
+ @@app_worker_id = ENV.fetch("APP_WORKER_ID", 0)
21
+ @@epoch = Time.utc(2020)
22
+ @@counter_time = 0
23
+ @@counter = 0
24
+ @@check_proc = nil
25
+
26
+ # Set your default snowflake default id. This is a 10-bit number (0..1023)
27
+ # that designates your: datacenter, machine, and/or process that generated it.
28
+ # This can be overridden by setting the environment variable APP_WORKER_ID
29
+ # or by the caller.
30
+ # Usage (configuration): MakeId.app_worker_id = 123
31
+ def self.app_worker_id=(id)
32
+ @@app_worker_id = id.to_i & 0x3ff
33
+ end
34
+
35
+ # Returns the current worker id
36
+ def self.app_worker_id
37
+ @@app_worker_id
38
+ end
39
+
40
+ # Set a custom check digit proc that takes the id string and base as argumentsA
41
+ # and returns a character to append to the end of the id.
42
+ def self.check_proc=(proc)
43
+ @@check_proc = proc
44
+ end
45
+
46
+ # Sets the start year for snowflake epoch
47
+ def self.epoch=(arg)
48
+ @@epoch = arg.is_a?(Time) ? arg : Time.utc(arg)
49
+ end
50
+
51
+ def self.epoch
52
+ @@epoch
53
+ end
54
+
55
+ def self.application_epoch
56
+ Time.now.to_i - @@epoch.to_i
57
+ end
58
+
59
+ ##############################################################################
60
+ # Random Strings
61
+ ##############################################################################
62
+
63
+ # Returns a random alphanumeric string of the given base, default of 62.
64
+ # Base 64 uses URL-safe characters. Bases 19-32 and below use a special
65
+ # character set that avoids visually ambiguous characters. Other bases
66
+ # utilize the full alphanumeric characer set (digits, lower/upper letters).
67
+ def self.random(size = 16, base: 62)
68
+ raise "Base must be between 2 and 62, or 64, not #{base}" unless base < 63 || base == 64
69
+ if base == 62
70
+ SecureRandom.alphanumeric(size)
71
+ elsif base == 64
72
+ SecureRandom.urlsafe_base64(size)
73
+ else
74
+ alpha = (base <= 32) ? CHARS32 : CHARS62
75
+ (1..size).map { alpha[SecureRandom.rand(base - 1)] }.join
76
+ end
77
+ end
78
+
79
+ ##############################################################################
80
+ # Integers
81
+ ##############################################################################
82
+
83
+ # Random Integer ID
84
+ def self.random_id(bytes: 8, base: 10, absolute: true, check_digit: false)
85
+ id = SecureRandom.random_number(2**(bytes * 8) - 2) + 1 # +1 to avoid zero
86
+ id = id.abs if absolute
87
+ id = int_to_base(id, base) unless base == 10
88
+ id = append_check_digit(id, base) if check_digit
89
+ id
90
+ end
91
+
92
+ ##############################################################################
93
+ # UUID - Universally Unique Identifier
94
+ ##############################################################################
95
+
96
+ # Returns a (securely) random generated UUID v4
97
+ def self.uuid
98
+ SecureRandom.uuid
99
+ end
100
+
101
+ # Accepts a hext UUID string and returns the integer value in the given base.
102
+ # If base is specified, it will convert to that base using MakeId utilities.
103
+ def self.uuid_to_base(uuid, base = 10)
104
+ int = uuid.delete("-").to_i(16)
105
+ (base == 10) ? int : int_to_base(int, base)
106
+ end
107
+
108
+ ##############################################################################
109
+ # Nano Id - Simple, secure URL-friendly unique string ID generator
110
+ ##############################################################################
111
+
112
+ # Generates a "nano id", a string of random characters of the given alphabet,
113
+ # suitable for URL's or where you don't want to show a sequential number.
114
+ # A check digit is added to the end to help prevent typos.
115
+ def self.nano_id(size: 20, base: 62, check_digit: true)
116
+ # alpha = (base <= 32) ? CHARS32 : CHARS62
117
+ size -= 1 if check_digit
118
+ id = random(size, base: base)
119
+ check_digit ? append_check_digit(id, base) : id
120
+ end
121
+
122
+ # Given a nano_id, replaces visually ambiguous characters and verifies the
123
+ # check digit. Returns the corrected id or nil if the check digit is invalid.
124
+ def self.verify_base32_id(nanoid)
125
+ nanoid.gsub!(/[oO]/, "0")
126
+ nanoid.gsub!(/[lLiI]/, "1")
127
+ nanoid.downcase
128
+ valid_check_digit?(nanoid, base: 32)
129
+ end
130
+
131
+ # Manual Id is a code and/or identifier that is manually entered by a user.
132
+ # Examples of this would be a Two-Factor Authentication challenge, a code
133
+ # used for confirmation, redemption, or a short-term record lookup code
134
+ # (like an airline ticket/itenerary code)
135
+ # It uses a base-32 (non-ambiguous character set) by default,
136
+ def self.manual_id(size: 6, base: 32, check_digit: false)
137
+ base = 32 if base > 36 # For upcasing
138
+ nano_id(size: size, base: base, check_digit: check_digit).upcase
139
+ end
140
+
141
+ def self.fix_manual_id(id, base: 32, check_digit: false)
142
+ if base == 32
143
+ id = id.gsub(/[oO]/, "0")
144
+ id = id.gsub(/[lLiI]/, "1")
145
+ end
146
+ id = valid_check_digit?(id.downcase, base: 32) if check_digit
147
+ id.upcase
148
+ end
149
+
150
+ ##############################################################################
151
+ # Event Id - A nano_id, but timestamped event identifier: YMDHMSUUrrrrc
152
+ ##############################################################################
153
+
154
+ # Returns an event timestamp of the form YMDHMSUUrrrrc
155
+ def self.event_id(size: 12, check_digit: false, time: nil)
156
+ time ||= Time.new.utc
157
+ usec = int_to_base((time.subsec.to_f * 62 * 62).to_i, 62)
158
+ parts = [
159
+ CHARS62[time.year % @@epoch.year],
160
+ CHARS62[time.month],
161
+ CHARS62[time.day],
162
+ CHARS62[time.hour],
163
+ CHARS62[time.min],
164
+ CHARS62[time.sec],
165
+ usec.rjust(2, "0") # 2-chars, 0..3843
166
+ ]
167
+ nano_size = size - 8 - (check_digit ? 1 : 0)
168
+ parts << nano_id(size: nano_size, base: 62) if nano_size > 0
169
+ id = check_digit ? append_check_digit(parts.join, 62) : parts.join
170
+ id[0, size]
171
+ end
172
+
173
+ # Returns a 16-character request id string in Base32 of format: YMDHsssuuqqwwrrr
174
+ # Use substring [3, 8] (Hsssuuqq) for a short 8-character version, easier for human scanning.
175
+ def self.request_id(time: nil, sequence_method: :counter)
176
+ time ||= Time.new
177
+ seconds = time.to_i - Time.new(time.year, time.month, time.day, time.hour).to_i # time.utc.hour??
178
+
179
+ sequence = if sequence_method == :counter
180
+ next_millisecond_sequence(((Time.now.utc.to_f - @@epoch.to_i) * 1000).to_i)
181
+ elsif sequence_method == :random
182
+ SecureRandom.random_number(4095)
183
+ end
184
+
185
+ [
186
+ CHARS62[time.year % @@epoch.year],
187
+ CHARS62[time.month],
188
+ CHARS62[time.day], # "-",
189
+ CHARS62[time.hour].downcase,
190
+ int_to_base(seconds, 32).rjust(3, "0"), # 3 chars
191
+ int_to_base((time.subsec.to_f * 32 * 32).to_i, 32), # 2 chars
192
+ sequence.to_s(32).rjust(2, "0"), # 2 chars "-",
193
+ (app_worker_id % 1024).to_s(32).rjust(2, "0"), # 2 chars
194
+ random(3, base: 32)
195
+ ].join
196
+ end
197
+
198
+ ##############################################################################
199
+ # Snowflake Id - Epoch + millisecond + worker_id id + sequence number
200
+ # Snowflakes are a form of unique identifier used in distributed computing.
201
+ # Uses an epoch time with miliseconds (41 bits), a worker_id id of where it was
202
+ # created (datacenter, machine, process, 10 bits), and a sequence number (12 bits).
203
+ ##############################################################################
204
+
205
+ # Returns an 8-byte integer snowflake id that can be reverse parsed.
206
+ # sequence_counter can be :counter for a rotating integer, or :random
207
+ def self.snowflake_id(worker_id: nil, base: 10, sequence_method: :counter)
208
+ milliseconds = ((Time.now.utc.to_f - @@epoch.to_i) * 1000).to_i
209
+ worker_id ||= app_worker_id
210
+ sequence = 0
211
+ if sequence_method == :counter
212
+ sequence = next_millisecond_sequence(milliseconds)
213
+ elsif sequence_method == :random
214
+ sequence = SecureRandom.random_number(4095)
215
+ end
216
+
217
+ id = combine_snowflake_parts(milliseconds, worker_id, sequence)
218
+ (base == 10) ? id : int_to_base(id, base)
219
+ end
220
+
221
+ # Returns uuid with Unix epoch time sort in format: ssssssss-uuuw-wwrr-rrrr-rrrrrrrrrrrr
222
+ # Specify `application_epoch: true` to use instead of Unix epoch
223
+ def self.snowflake_uuid(time: nil, format: true, worker_id: nil, application_epoch: false)
224
+ time ||= Time.new
225
+ seconds = time.to_i
226
+ seconds -= @@epoch.to_i if application_epoch
227
+ worker_id ||= app_worker_id
228
+ parts = [
229
+ seconds.to_s(16).rjust(8, "0"),
230
+ (time.subsec.to_f * 1000).to_i.to_s(16).rjust(3, "0"),
231
+ (worker_id % 1024).to_s(16).rjust(3, "0"),
232
+ SecureRandom.hex(9)
233
+ ]
234
+ id = append_check_digit(parts.join, 16).downcase
235
+ format ? "#{id[0..7]}-#{id[8..11]}-#{id[12..15]}-#{id[16..19]}-#{id[20..31]}" : id
236
+ end
237
+
238
+ # Returns UUID with columnar date parts: yyyymmdd-hhmm-ssuu-uwww-rrrrrrrrrrrr
239
+ def self.snowflake_datetime_uuid(time: nil, format: true, worker_id: nil, utc: true)
240
+ time ||= Time.new
241
+ time = time.utc if utc
242
+ worker_id ||= app_worker_id
243
+ id = [
244
+ time.year,
245
+ time.month.to_s.rjust(2, "0"),
246
+ time.day.to_s.rjust(2, "0"),
247
+ time.hour.to_s.rjust(2, "0"),
248
+ time.min.to_s.rjust(2, "0"),
249
+ time.sec.to_s.rjust(2, "0"),
250
+ (time.subsec.to_f * 1000).to_i.to_s(16).rjust(3, "0"),
251
+ (worker_id % 1024).to_s(16).rjust(3, "0"),
252
+ SecureRandom.hex(6)
253
+ ].join
254
+ format ? "#{id[0..7]}-#{id[8..11]}-#{id[12..15]}-#{id[16..19]}-#{id[20..31]}" : id
255
+ end
256
+
257
+ # Creates the final snowflake by bit-mapping the constituent parts into the whole
258
+ def self.combine_snowflake_parts(milliseconds, worker_id, sequence)
259
+ id = milliseconds & 0x1ffffffffff # 0 (sign) + lower 41bits
260
+ id <<= 10
261
+ id |= worker_id & 0x3ff # 10bits (0..1023)
262
+ id <<= 12
263
+ id |= (sequence & 0xfff) # 12 bits (0..4095)
264
+
265
+ id
266
+ end
267
+
268
+ def self.next_millisecond_sequence(milliseconds)
269
+ sequence = 0
270
+ semaphore = Mutex.new
271
+
272
+ semaphore.synchronize do
273
+ if @@counter_time != milliseconds
274
+ @@counter_time = milliseconds
275
+ @@counter = 0
276
+ end
277
+ sequence = @@counter % 4095
278
+ @@counter += 1
279
+ end
280
+
281
+ sequence
282
+ end
283
+
284
+ # Build an integer value from pairs of [bits, value]
285
+ def self.pack_int_parts(*pairs)
286
+ int = 0
287
+ pairs.each do |bits, value|
288
+ int = (int << bits) | (value & ((1 << bits) - 1))
289
+ end
290
+ int
291
+ end
292
+
293
+ ##############################################################################
294
+ # Base Conversions
295
+ ##############################################################################
296
+
297
+ # Takes an integer and a base (from 2 to 62) and converts the number.
298
+ # Ruby's int.to_s(base) only goes to 36. Base 32 is special as it does not
299
+ # contain visually ambiguous characters (1, not i, I, l, L) and (0, not o or O)
300
+ # Which is useful for serial numbers or codes the user has to read or type
301
+ def self.int_to_base(int, base = 62, check_digit: false)
302
+ int = int.to_i
303
+ if base == 10
304
+ id = int.to_s
305
+ elsif base == 64
306
+ id = Base64.urlsafe_encode64(int.to_s).delete("=")
307
+ elsif base == 32 || base > 36
308
+ alpha = (base <= 32) ? CHARS32 : CHARS62
309
+ id = ""
310
+ while int > (base - 1)
311
+ id = alpha[int % base] + id
312
+ int /= base
313
+ end
314
+ id = alpha[int] + id
315
+ else
316
+ id = int.to_s(base)
317
+ end
318
+ check_digit ? append_check_digit(id, base) : id
319
+ end
320
+
321
+ singleton_class.alias_method :to_base, :int_to_base
322
+
323
+ # Parses a string as a base n number and returns its decimal integer value
324
+ def self.base_to_int(string, base = 62, check_digit: false)
325
+ # TODO check_digit
326
+ if base == 64
327
+ int = Base64.urlsafe_decode64(string.to_s + "==")
328
+ elsif base == 32 || base > 36
329
+ alpha = (base <= 32) ? CHARS32 : CHARS62
330
+ string = string.to_s
331
+ int = 0
332
+ string.each_char { |c| int = int * base + alpha.index(c) }
333
+ else
334
+ int = string.to_i(base)
335
+ end
336
+ int
337
+ end
338
+
339
+ singleton_class.alias_method :from_base, :base_to_int
340
+
341
+ ##############################################################################
342
+ # Check Digit
343
+ ##############################################################################
344
+
345
+ # Adds a check digit to the end of an id string. This check digit is derived
346
+ # from the CRC-32 (Cyclical Redundancy Check) value of the id string
347
+ def self.append_check_digit(id, base = 10)
348
+ id.to_s + compute_check_digit(id, base)
349
+ end
350
+
351
+ # Returns a character computed using the CRC32 algorithm
352
+ # Uses a pre-defined check_proc if configured. See check_proc=().
353
+ def self.compute_check_digit(id, base = 10)
354
+ return @@check_proc.call(id, base) if @@check_proc.is_a?(Proc)
355
+ int_to_base(Zlib.crc32(id.to_s) % base, base)
356
+ end
357
+
358
+ # Takes an id with a check digit and return true if the check digit matches
359
+ def self.valid_check_digit?(id, base = 10)
360
+ id == append_check_digit(id[0..-2], base)
361
+ end
362
+ end
data/sig/make_id.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module MakeId
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,71 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: make_id
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Allen Fair
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-10-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: base64
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: MakeId is a collection of record Identifier generators
28
+ email:
29
+ - allen.fair@gmail.com
30
+ executables:
31
+ - make-id
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".rspec"
36
+ - ".standard.yml"
37
+ - CODE_OF_CONDUCT.md
38
+ - LICENSE
39
+ - LICENSE.txt
40
+ - README.md
41
+ - Rakefile
42
+ - bin/make-id
43
+ - lib/make_id.rb
44
+ - lib/make_id/version.rb
45
+ - sig/make_id.rbs
46
+ homepage: https://github.com/afair/make_id
47
+ licenses:
48
+ - MIT
49
+ metadata:
50
+ homepage_uri: https://github.com/afair/make_id
51
+ source_code_uri: https://github.com/afair/make_id
52
+ post_install_message:
53
+ rdoc_options: []
54
+ require_paths:
55
+ - lib
56
+ required_ruby_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: 3.0.0
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ requirements: []
67
+ rubygems_version: 3.5.20
68
+ signing_key:
69
+ specification_version: 4
70
+ summary: MakeId provides a collection of record Identifier generators
71
+ test_files: []