### Configure custom epoch start time for TSID generation Source: https://context7.com/luismedel/tsid-python/llms.txt This example shows how to configure TSIDGenerator with custom epoch start times, including the standard Unix epoch and a specific application launch date. It demonstrates how the generated TSID timestamp relates to the configured epoch. ```python from datetime import datetime import time from tsidpy import TSIDGenerator, TSID # Use Unix epoch (1970-01-01) instead of default (2020-01-01) unix_epoch = datetime.fromisoformat('1970-01-01T00:00:00+00:00') unix_epoch_ms = unix_epoch.timestamp() * 1000 generator = TSIDGenerator(node=1, epoch=unix_epoch_ms) tsid = generator.create() # Timestamp is now milliseconds since 1970 unix_timestamp = tsid.timestamp current_time_ms = time.time() * 1000 print(f"TSID timestamp: {unix_timestamp}") print(f"Current time: {current_time_ms}") print(f"Difference: {current_time_ms - unix_timestamp} ms") # Custom epoch for application launch date app_launch = datetime(2023, 1, 1, 0, 0, 0) app_epoch_ms = app_launch.timestamp() * 1000 app_generator = TSIDGenerator(node=1, epoch=app_epoch_ms) app_tsid = app_generator.create() print(f"App TSID: {app_tsid}") print(f"Days since launch: {(app_tsid.timestamp - app_epoch_ms) / 1000 / 86400}") ``` -------------------------------- ### Database Primary Key Usage with TSID Source: https://context7.com/luismedel/tsid-python/llms.txt This Python example illustrates using TSIDs as efficient and sortable primary keys in a database. It shows how to configure a `TSIDGenerator` for a specific cluster, generate IDs, and demonstrates SQL insertion using both numeric and string representations of the TSID. It also includes an example of querying records within a time range. ```python from tsidpy import TSID, TSIDGenerator import time # Configure generator for your cluster # Example: 256 database shards, using 8 bits for node shard_id = 42 generator = TSIDGenerator(node=shard_id, node_bits=8) # Generate ID for new database record user_id = generator.create() # Store as BIGINT (64-bit integer) in database sql_insert = f""" INSERT INTO users (id, name, email, created_at) VALUES ({user_id.number}, 'John Doe', 'john@example.com', NOW()) """ # Or store as VARCHAR(13) using base32 string sql_insert_str = f""" INSERT INTO users (id, name, email, created_at) VALUES ('{user_id}', 'Jane Doe', 'jane@example.com', NOW()) """ # Query optimization with TSID range # Get all records from last hour one_hour_ago = (time.time() - 3600) * 1000 min_tsid = TSID((int(one_hour_ago - generator._epoch) << 22)) sql_query = f""" SELECT * FROM users WHERE id >= {min_tsid.number} ORDER BY id DESC """ # Index automatically sorts by creation time # CREATE INDEX idx_users_id ON users(id) print(f"User ID: {user_id.number}") print(f"User ID (string): {user_id}") print(f"Created at: {user_id.datetime}") print(f"Min TSID for range: {min_tsid.number}") ``` -------------------------------- ### Install tsid-python Library Source: https://github.com/luismedel/tsid-python/blob/master/README.md Install the tsid-python library using pip. This is the primary dependency for using the TSID generation functionalities. ```bash pip install tsidpy ``` -------------------------------- ### Convert TSID to Integer and String in Python Source: https://github.com/luismedel/tsid-python/blob/master/README.md Shows how to obtain the numerical integer representation and the standard string representation of a generated TSID. It also includes an example of converting the TSID to its hexadecimal string format. ```python # Create a TSID as an `int`: >>> TSID.create().number 432511671823499267 # Create a TSID as a `str`: >>> str(TSID.create()) '0C04Q2BR40003' # Create a TSID as an hexadecimal `str`: >>> TSID.create().to_string('x') '06009712f0400003' ``` -------------------------------- ### Configure Custom TSID Generator in Python Source: https://context7.com/luismedel/tsid-python/llms.txt Illustrates how to create and configure a `TSIDGenerator` with custom node IDs and bit allocations for node and counter parts. It shows examples for different cluster sizes and throughput requirements, including automatic node ID generation and setting a custom generator as the default. ```python from tsidpy import TSIDGenerator, TSID # Basic generator with custom node ID (default 10 bits for node) generator = TSIDGenerator(node=42, node_bits=10) tsid = generator.create() # Max node value with 10 bits: 2^10 - 1 = 1023 # Max counter value: 2^12 - 1 = 4095 (12 bits remaining) # Generator with more node bits for larger clusters large_cluster_gen = TSIDGenerator(node=5000, node_bits=14) # Max node: 16383, Max counter: 255 (8 bits for counter) # Generator with fewer node bits for higher throughput high_throughput_gen = TSIDGenerator(node=7, node_bits=3) # Max node: 7, Max counter: 524287 (19 bits for counter) # Random node ID (automatically generated if not specified) auto_node_gen = TSIDGenerator(node_bits=10) # Node ID will be randomly assigned # Generate multiple TSIDs for _ in range(5): tsid = generator.create() print(f"{tsid} - {tsid.number}") # Set as default generator for TSID.create() TSID.set_default_generator(generator) tsid = TSID.create() # Now uses custom generator ``` -------------------------------- ### TSID Comparison and Sorting Source: https://context7.com/luismedel/tsid-python/llms.txt This Python example demonstrates the natural ordering of TSIDs, which are designed to be sortable by their creation time. It generates a sequence of TSIDs with small delays between them and asserts their chronological order. It also shows how sorting a shuffled list of TSIDs correctly restores the original order. ```python from tsidpy import TSID import time import random # Generate TSIDs over time tsids = [] for i in range(5): tsid = TSID.create() tsids.append(tsid) if i < 4: time.sleep(0.01) # 10ms delay # TSIDs are naturally ordered by creation time assert tsids[0] < tsids[1] < tsids[2] < tsids[3] < tsids[4] # Sorting works as expected shuffled = tsids.copy() random.shuffle(shuffled) shuffled.sort() assert shuffled == tsids ``` -------------------------------- ### Use custom random function for deterministic TSID testing Source: https://context7.com/luismedel/tsid-python/llms.txt This snippet illustrates how to provide a custom random function to TSIDGenerator for deterministic ID generation, useful in testing scenarios. It includes examples for a zero-incrementing counter and cryptographically secure random numbers. ```python from tsidpy import TSIDGenerator, TSID # Deterministic counter (always starts at 0) def zero_counter(bits): return 0 deterministic_gen = TSIDGenerator( node=1, node_bits=10, random_fn=zero_counter ) # Generate predictable IDs for testing tsid1 = deterministic_gen.create() tsid2 = deterministic_gen.create() tsid3 = deterministic_gen.create() # Counter increments: 1, 2, 3 (started at 0, incremented each time) print(f"TSID 1 random: {tsid1.random}") # 1 print(f"TSID 2 random: {tsid2.random}") # 2 print(f"TSID 3 random: {tsid3.random}") # 3 # Custom random with specific distribution import secrets def crypto_random(bits): """Use cryptographically secure random for production.""" return secrets.randbits(bits) secure_gen = TSIDGenerator(node=5, random_fn=crypto_random) secure_tsid = secure_gen.create() print(f"Secure TSID: {secure_tsid}") # Seeded random for reproducible tests import random def seeded_random(bits): return random.getrandbits(bits) random.seed(42) test_gen = TSIDGenerator(node=1, random_fn=seeded_random) test_tsid = test_gen.create() ``` -------------------------------- ### Get TSID Timestamp Source: https://github.com/luismedel/tsid-python/blob/master/README.md Retrieve the creation timestamp of a TSID as a Unix timestamp (in milliseconds) using the `.timestamp` property. ```python tsid.timestamp ``` -------------------------------- ### Thread-safe concurrent TSID generation in Python Source: https://context7.com/luismedel/tsid-python/llms.txt This example demonstrates how to generate TSIDs concurrently from multiple threads using tsid-python. The TSIDGenerator is inherently thread-safe, and this snippet shows how to collect generated IDs from different threads. ```python from tsidpy import TSIDGenerator, TSID import threading import time # Create a shared generator (thread-safe by default) generator = TSIDGenerator(node=1, node_bits=10) # Storage for generated IDs generated_ids = [] lock = threading.Lock() def generate_ids(thread_id, count): """Generate IDs from multiple threads.""" local_ids = [] for _ in range(count): tsid = generator.create() local_ids.append(tsid.number) with lock: generated_ids.extend(local_ids) print(f"Thread {thread_id} generated {count} IDs") ``` -------------------------------- ### Generate Twitter Snowflake-style IDs using TSID Source: https://context7.com/luismedel/tsid-python/llms.txt This snippet demonstrates how to generate Twitter Snowflake-compatible IDs using the TSIDGenerator. It customizes the node bits, epoch, and initializes the counter to start at 0, bypassing randomization. ```python from datetime import datetime from tsidpy import TSIDGenerator, TSID # - 10 bits for node: 5 bits datacenter + 5 bits worker # - Custom epoch: 2010-11-04T01:42:54.657Z # - Counter starts at 0 (not randomized) datacenter = 1 # 0-31 worker = 1 # 0-31 node = datacenter << 5 | worker # Combine into 10-bit node ID epoch = datetime.fromisoformat('2010-11-04T01:42:54.657+00:00') epoch_ms = epoch.timestamp() * 1000 twitter_generator = TSIDGenerator( node=node, node_bits=10, epoch=epoch_ms, random_fn=lambda n: 0 # Counter starts at 0, not random ) # Generate Twitter Snowflake-style IDs snowflake_id = twitter_generator.create() print(f"Snowflake ID: {snowflake_id.number}") print(f"Timestamp: {snowflake_id.datetime}") # Use as default TSID.set_default_generator(twitter_generator) tsid = TSID.create() # Now generates Snowflake-compatible IDs ``` -------------------------------- ### Get TSID as Integer Source: https://github.com/luismedel/tsid-python/blob/master/README.md Access the internal integer representation of a TSID object using the `.number` property. This provides the raw numerical value of the TSID. ```python from tsidpy import TSID TSID.create(432511671823499267).number ``` -------------------------------- ### Generate Discord Snowflake-compatible IDs using TSID Source: https://context7.com/luismedel/tsid-python/llms.txt This code configures and generates TSIDs compatible with Discord's Snowflake ID format. It uses a custom epoch and a 10-bit node configuration, leveraging the default random counter start with 12 bits. ```python from datetime import datetime from tsidpy import TSIDGenerator, TSID # Discord Snowflake configuration: # - 10 bits for node: 5 bits worker + 5 bits process # - Custom epoch: 2015-01-01T00:00:00.000Z # - Counter uses 12 bits with random start worker = 1 # 0-31 process = 1 # 0-31 node = worker << 5 | process # Combine into 10-bit node ID epoch = datetime.fromisoformat("2015-01-01T00:00:00.000+00:00") epoch_ms = epoch.timestamp() * 1000 discord_generator = TSIDGenerator( node=node, node_bits=10, epoch=epoch_ms # random_fn uses default (random counter start) ) # Generate Discord Snowflake-style IDs discord_id = discord_generator.create() print(f"Discord ID: {discord_id.number}") print(f"String: {discord_id}") print(f"Worker: {worker}, Process: {process}") print(f"Created: {discord_id.datetime}") # Set as default for all subsequent TSID.create() calls TSID.set_default_generator(discord_generator) ``` -------------------------------- ### Get TSID as String Source: https://github.com/luismedel/tsid-python/blob/master/README.md Convert a TSID object into its Crockford's base 32 string representation using the `.to_string()` method or by casting to `str`. The resulting string is always 13 characters long. ```python from tsidpy import TSID tsid: str = TSID.create().to_string() print(tsid) ``` ```python from tsidpy import TSID tsid: str = str(TSID.create()) print(tsid) ``` -------------------------------- ### Distributed System Node Identification Source: https://context7.com/luismedel/tsid-python/llms.txt This Python snippet shows how to configure unique node identifiers for distributed systems using `TSIDGenerator`. It presents three methods for determining node IDs: manual assignment, hash-based generation from the hostname, and environment variable lookup. It also demonstrates generating IDs with node tracking and extracting the node ID from a TSID. ```python from tsidpy import TSIDGenerator, TSID import socket import hashlib import os # Method 1: Manual node assignment datacenter = 2 # 0-7 (3 bits) server = 5 # 0-31 (5 bits) node_id = (datacenter << 5) | server # 8-bit node ID generator1 = TSIDGenerator(node=node_id, node_bits=8) # Method 2: Hash-based node ID from hostname def get_node_from_hostname(bits): hostname = socket.gethostname() hash_value = int(hashlib.md5(hostname.encode()).hexdigest(), 16) max_value = (2 ** bits) - 1 return hash_value % (max_value + 1) node_id_auto = get_node_from_hostname(10) generator2 = TSIDGenerator(node=node_id_auto, node_bits=10) # Method 3: Environment-based node ID node_id_env = int(os.environ.get('NODE_ID', 0)) generator3 = TSIDGenerator(node=node_id_env, node_bits=10) # Generate IDs with node tracking tsid = generator1.create() print(f"Generator 1 - Node: {node_id}, TSID: {tsid}") tsid = generator2.create() print(f"Generator 2 - Node: {node_id_auto}, TSID: {tsid}") # Extract node ID from TSID (for 10-bit node) counter_bits = 22 - 10 # 12 bits extracted_node = (tsid.random >> counter_bits) print(f"Extracted node from TSID: {extracted_node}") # Validate node ID range max_node = (2 ** 10) - 1 assert node_id_auto <= max_node, f"Node {node_id_auto} exceeds max {max_node}" ``` -------------------------------- ### Parse TSID from Various Formats in Python Source: https://context7.com/luismedel/tsid-python/llms.txt Demonstrates how to reconstruct TSID objects from different string representations (base32, hexadecimal, base-10, base-62), byte arrays, and direct integer values. Also shows that TSIDs are comparable and sortable. ```python from tsidpy import TSID # From canonical base32 string tsid1 = TSID.from_string('0123456789ABC') # From lowercase base32 string tsid2 = TSID.from_string('0123456789abc', 's') # From hexadecimal string tsid3 = TSID.from_string('0575FDC1787DAFA0', 'X') tsid4 = TSID.from_string('0575fdc1787dafa0', 'x') # From base-10 string tsid5 = TSID.from_string('437283649808777971', 'd') # From base-62 string tsid6 = TSID.from_string('WIlLsHwljH', 'z') # From bytes (8 bytes, big-endian) tsid7 = TSID.from_bytes(b'\x00\x00\x00\x00\x00\x00\x00\x01') # From integer directly tsid8 = TSID(432511671823499267) # All TSIDs are comparable and sortable assert tsid1 < tsid8 tsid_list = [tsid8, tsid1, tsid3] tsid_list.sort() # Sorts by creation time ``` -------------------------------- ### Python: Use TSIDs in Sets and Dictionaries Source: https://context7.com/luismedel/tsid-python/llms.txt Illustrates how to leverage the hashable nature of TSIDs in Python by adding them to a set to find unique IDs and using them as keys in a dictionary. ```python tsid_set = set(tsids) print(f"Unique TSIDs: {len(tsid_set)}") tsid_dict = {t: f"Record {i}" for i, t in enumerate(tsids)} print(f"Dict lookup: {tsid_dict[oldest]}") ``` -------------------------------- ### Spawn Multiple Threads for ID Generation Source: https://context7.com/luismedel/tsid-python/llms.txt This snippet demonstrates how to spawn multiple threads to concurrently generate IDs using the `threading` module. It then waits for all threads to complete and verifies the uniqueness and sortability of the generated IDs. ```python import threading # Assume generate_ids and generated_ids are defined elsewhere # Example placeholder: def generate_ids(thread_id, num_ids): for _ in range(num_ids): # In a real scenario, this would generate and add IDs to a shared list pass generated_ids = [] # Placeholder for demonstration threads = [] for i in range(10): t = threading.Thread(target=generate_ids, args=(i, 1000)) threads.append(t) t.start() for t in threads: t.join() print(f"Total IDs generated: {len(generated_ids)}") print(f"Unique IDs: {len(set(generated_ids))}") print(f"All unique: {len(generated_ids) == len(set(generated_ids))}") sorted_ids = sorted(generated_ids) is_sorted = generated_ids == sorted_ids print(f"IDs are sorted: {is_sorted}") ``` -------------------------------- ### Create Discord Snowflake-like TSID Generator Source: https://github.com/luismedel/tsid-python/blob/master/README.md Instantiate a `TSIDGenerator` that generates TSIDs resembling Discord Snowflakes. Key configurations include worker ID, process ID, a specific epoch, and a random initial counter. ```python from tsidpy import TSID, TSIDGenerator from datetime import datetime worker: int = 1 process: int = 1 node: int = worker << 5 | process epoch: datetime = datetime.fromisoformat("2015-01-01T00:00:00.000Z") discord_generator: TSIDGenerator = TSIDGenerator(node=node, node_bits=10, epoch=epoch.timestamp() * 1000) # use the generator tsid: TSID = discord_generator.create() ``` -------------------------------- ### Create a TSID in Python Source: https://github.com/luismedel/tsid-python/blob/master/README.md Demonstrates the basic usage of creating a Time-Sorted Unique Identifier (TSID) using the `tsidpy` library. This is the core function for generating new TSIDs. ```python from tsidpy import TSID tsid: TSID = TSID.create() ``` -------------------------------- ### Create and Access TSID Properties in Python Source: https://context7.com/luismedel/tsid-python/llms.txt Generates a new TSID using the default generator and demonstrates how to access its numerical, string (base32), hexadecimal, timestamp, datetime, and random components. ```python from tsidpy import TSID # Create a new TSID tsid = TSID.create() # Get as integer (64-bit) tsid_int = tsid.number # Output: 432511671823499267 # Get as string (13 chars, base32) tsid_str = str(tsid) # Output: '0C04Q2BR40003' # Get as hexadecimal tsid_hex = tsid.to_string('x') # Output: '06009712f0400003' # Access timestamp (milliseconds since epoch) timestamp = tsid.timestamp # Output: 1680948418241.0 # Access datetime dt = tsid.datetime # Output: datetime.datetime(2023, 4, 8, 12, 6, 58, 241000) # Access random component random_bits = tsid.random # Output: 3 (22-bit random value) ``` -------------------------------- ### Python: Compare TSIDs Source: https://context7.com/luismedel/tsid-python/llms.txt Demonstrates the use of comparison operators (>, <, !=, ==) to compare Time-Sorted IDs (TSIDs) in Python. Assumes a list named 'tsids' is already populated. ```python newest = tsids[-1] oldest = tsids[0] assert newest > oldest assert oldest < newest assert newest != oldest assert oldest == tsids[0] ``` -------------------------------- ### Create TSID from String Source: https://github.com/luismedel/tsid-python/blob/master/README.md Instantiate a TSID object from its canonical 13-character string representation using the `TSID.from_string()` method. ```python from tsidpy import TSID tsid = TSID.from_string('0123456789ABC') ``` -------------------------------- ### Convert TSID to Different Encodings in Python Source: https://context7.com/luismedel/tsid-python/llms.txt Shows how to convert a TSID object into various string formats including base32 (uppercase and lowercase), hexadecimal (uppercase and lowercase), base-10 decimal, and base-62. It also demonstrates conversion to a byte array. ```python from tsidpy import TSID tsid = TSID.create() # Base32 uppercase (default, 13 chars) canonical = tsid.to_string('S') # Output: '0AWE5HZP3SKTK' # Base32 lowercase (URL-safe) lowercase = tsid.to_string('s') # Output: '0awe5hzp3sktk' # Hexadecimal uppercase (16 chars) hex_upper = tsid.to_string('X') # Output: '0571C58FEC3CCF53' # Hexadecimal lowercase hex_lower = tsid.to_string('x') # Output: '0571c58fec3ccf53' # Base-10 decimal string decimal = tsid.to_string('d') # Output: '437283649808777971' # Base-62 (shortest string representation) base62 = tsid.to_string('z') # Output: '0T5jFDIkmmy' # As bytes (8 bytes, big-endian) byte_array = tsid.to_bytes() # Output: b'\x00\x00\x00\x00\x06\x00\x97\x12' # String conversion and comparison assert str(tsid) == canonical assert tsid.number == int.from_bytes(byte_array, 'big') ``` -------------------------------- ### High-Throughput ID Generation Benchmark Source: https://context7.com/luismedel/tsid-python/llms.txt This Python snippet benchmarks the ID generation speed of `TSIDGenerator` configured for maximum throughput. It measures the time taken to generate a large number of IDs, calculates the throughput in IDs per second, and verifies for collisions and millisecond distribution. ```python from tsidpy import TSIDGenerator, TSID import time # Configure for maximum throughput (no node bits, 22-bit counter) high_speed_gen = TSIDGenerator(node=0, node_bits=0) # Max IDs per millisecond: 2^22 = 4,194,304 # Benchmark generation speed count = 100_000 start = time.time() ids = [] for _ in range(count): tsid = high_speed_gen.create() ids.append(tsid.number) elapsed = time.time() - start ids_per_second = count / elapsed print(f"Generated {count:,} IDs in {elapsed:.2f} seconds") print(f"Throughput: {ids_per_second:,.0f} IDs/second") # Verify no collisions unique_ids = len(set(ids)) print(f"Unique IDs: {unique_ids:,}/{count:,}") print(f"Collision rate: {(count - unique_ids) / count * 100:.4f}%") # Check millisecond distribution timestamps = [TSID(id).timestamp for id in ids] unique_timestamps = len(set(timestamps)) print(f"Unique milliseconds: {unique_timestamps}") print(f"Avg IDs per millisecond: {count / unique_timestamps:.0f}") ``` -------------------------------- ### Create Twitter Snowflake-like TSID Generator Source: https://github.com/luismedel/tsid-python/blob/master/README.md Initialize a `TSIDGenerator` configured to produce TSIDs similar to Twitter Snowflakes. This involves setting a specific node ID, number of node bits, epoch, and disabling randomness. ```python from tsidpy import TSID, TSIDGenerator from datetime import datetime datacenter: int = 1 worker: int = 1 node: int = datacenter << 5 | worker epoch: datetime = datetime.fromisoformat('2010-11-04T01:42:54.657Z') twitter_generator: TSIDGenerator = TSIDGenerator(node=node, node_bits=10, epoch=epoch.timestamp() * 1000, random_fn=lambda n: 0) # use the generator tsid: TSID = twitter_generator.create() ``` -------------------------------- ### Convert TSID to Lowercase String Source: https://github.com/luismedel/tsid-python/blob/master/README.md Obtain a lowercase version of the TSID's canonical string representation by calling `.to_string('s')`. ```python tsid.to_string('s') ``` -------------------------------- ### Set Default TSID Generator Source: https://github.com/luismedel/tsid-python/blob/master/README.md Configure the `TSID` class to use a specific `TSIDGenerator` instance as the default for `TSID.create()` calls. After setting, both `TSID.create()` and the specific generator's `create()` method will produce similar TSIDs. ```python TSID.set_default_generator(discord_generator) # at this point, you can use the default TSID.create() tsid: TSID = TSID.create() # or the generator tsid: TSID = discord_generator.create() ``` -------------------------------- ### TSIDGenerator Node ID Validation Source: https://github.com/luismedel/tsid-python/blob/master/README.md Illustrates the constraint on the `node` ID when initializing a `TSIDGenerator`. The `node` ID must be representable within the specified `node_bits`. Attempting to use a `node` ID that exceeds the bit limit will result in an error. ```python from tsidpy import TSIDGenerator gen0 = TSIDGenerator(node=0, node_bis=3) # ok gen1 = TSIDGenerator(node=1, node_bis=3) # ok ... gen7 = TSIDGenerator(node=7, node_bis=3) # ok # error: can't represent 8 with 3 bits gen8 = TSIDGenerator(node=8, node_bis=3) ``` -------------------------------- ### Python: Find TSIDs in Time Range Source: https://context7.com/luismedel/tsid-python/llms.txt Shows how to filter a list of TSIDs to find those within a specific time range using Python. It extracts a timestamp from a middle TSID and then iterates through the list to select recent TSIDs. ```python middle_time = tsids[2].timestamp recent_tsids = [t for t in tsids if t.timestamp >= middle_time] print(f"TSIDs since {middle_time}: {len(recent_tsids)}") ``` -------------------------------- ### Encode TSID to Base-62 Source: https://github.com/luismedel/tsid-python/blob/master/README.md Convert a TSID into its base-62 string representation by calling `.to_string('z')`. ```python tsid.to_string('z') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.