def test_ulid_from_time(): ulid1 = ULID.from_timestamp(time.time()) ulid2 = ULID.from_datetime(utcnow()) now = utcnow() t = time.time() assert ulid1.timestamp == pytest.approx(t) datetimes_almost_equal(ulid1.datetime, now) assert ulid2.timestamp == pytest.approx(t) datetimes_almost_equal(ulid2.datetime, now)
def test_idempotency(): ulid = ULID() assert ULID.from_bytes(ulid.bytes) == ulid assert ULID.from_str(str(ulid)) == ulid assert ULID.from_uuid(ulid.to_uuid()) == ulid assert ULID.from_int(int(ulid)) == ulid assert ULID.from_hex(ulid.hex) == ulid
def create_invoice(account_id, client_id, invoice): if not invoice.get('number'): invoice['number'] = next_invoice_num(account_id) invoice_id = str(ULID.from_datetime(invoice['issued_on'])) invoice['invoice_id'] = invoice_id invoice['client_id'] = client_id invoice_item = { **make_indexes( 'Invoice', PK=f'CLIENT#{client_id}', SK=f'#INVOICE#{invoice_id}', GSI1PK=f'INVOICE#{invoice_id}', GSI1SK=f'INVOICE#{invoice_id}', ), **dict_to_item(invoice) } ddb_client.transact_write_items(TransactItems=[ make_put_unique(invoice_item), make_put_unique( dict_to_item( { 'PK': f'ACCOUNT#{account_id}#INVOICENUMBER#{invoice["number"]}', 'SK': f'ACCOUNT#{account_id}#INVOICENUMBER#{invoice["number"]}', }, False)), ]) return invoice_id
def start_process(self, process, tasks: list) -> FanManagerResults: print(f"\n\nDEBUG Starting process: {process}") updated_process = ProcessDTO( process_name=process.process_name, process_id=str(ULID()), started=datetime.now().isoformat(), information=process.information, ) self.repository.save_process(updated_process) updated_tasks = [] for task in tasks: print(f"\nDEBUG Adding: {task.task_name}") new_task = TaskDTO( task.task_name, task.task_message, updated_process.process_id, updated_process.process_name, TASK_STATUS_FAN_OUT, datetime.now().isoformat(), datetime.now().isoformat(), ) self.repository.save_task(new_task) updated_tasks.append(new_task) event = FanEventDTO( self.event_source, EVENT_PROCESS_STARTED, updated_process.__dict__ ) self.notifier.send_message(event) return FanManagerResults(updated_process, updated_tasks, [event])
def test_comparison(): with freeze_time() as frozen_time: ulid1 = ULID() assert ulid1 == ulid1 assert ulid1 == int(ulid1) assert ulid1 == ulid1.bytes assert ulid1 == str(ulid1) assert (ulid1 == object()) is False frozen_time.tick() ulid2 = ULID() assert ulid1 < ulid2 assert ulid1 < int(ulid2) assert ulid1 < ulid2.bytes assert ulid1 < str(ulid2) with pytest.raises(TypeError): ulid1 < object()
def test_ulid(): ulid = ULID() t = time.time() now = utcnow() assert len(ulid.bytes) == constants.BYTES_LEN assert len(str(ulid)) == constants.REPR_LEN assert all(c in base32.ENCODE for c in str(ulid)) assert isinstance(ulid.to_uuid(), uuid.UUID) assert isinstance(ulid.timestamp, float) assert ulid.timestamp == pytest.approx(t) assert isinstance(ulid.datetime, datetime) datetimes_almost_equal(ulid.datetime, now)
def on_mutations_created(items): nonlocal total progress.update() total += len(items) for path, delta in items: # TODO: replace ULID with a content addressable hash. uid = ULID().to_uuid() # delta is a compressed unified diff db[lexode.pack([1, uid])] = lexode.pack([path, delta])
def test_ulid_monotonic_sorting(tick): ulids = [] initial_time = utcnow() with freeze_time(initial_time) as frozen_time: for i in range(1, 11): ulids.append(ULID()) frozen_time.move_to(initial_time + timedelta(seconds=i * tick)) assert_sorted(ulids) assert_sorted([str(v) for v in ulids]) assert_sorted([int(v) for v in ulids]) assert_sorted([v.bytes for v in ulids])
def human_readable_ulid(ulid: ULID) -> "str": """ Formats the timestamp part of the ULID as a human readable datetime. Uses "T" as the date/time separator as per RFC3339, hyphen as the datetime field separator to ensure broad filesystem compatibility, and underscore as the datetime/randomness separator. ULIDs have millisecond timestamps, but strftime can only format microseconds, so we need to chop off the last three characters. """ datetime_string = ulid.timestamp().datetime.strftime( "%Y-%m-%dT%H-%M-%S-%f")[:-3] return f"{datetime_string}Z_{ulid.randomness()}"
def create_account(account): account['account_id'] = str(ULID()) account_item = { **make_indexes('Account', PK=f'ACCOUNT#{account["account_id"]}', SK=f'ACCOUNT#{account["account_id"]}'), **dict_to_item(account) } ddb_client.transact_write_items(TransactItems=[ make_put_unique(account_item), make_put_unique( dict_to_item( { 'PK': f'ACCOUNTEMAIL#{account["email"]}', 'SK': f'ACCOUNTEMAIL#{account["email"]}', }, False)), ]) return account['account_id']
def create_line_item(invoice_id, line_item): line_item_id = str(ULID()) line_item['line_item_id'] = line_item_id line_item['invoice_id'] = invoice_id ddb_client.put_item( TableName=table_name, Item={ **make_indexes( 'LineItem', PK=f'INVOICE#{invoice_id}#LINEITEM#{line_item_id}', SK=f'INVOICE#{invoice_id}#LINEITEM#{line_item_id}', GSI1PK=f'INVOICE#{invoice_id}', GSI1SK=f'LINEITEM#{line_item_id}', ), **dict_to_item(line_item) }) return line_item_id
async def send_templated_message( msg: TemplatedMessage, client_settings: ClientSettings = Depends(identify_client)): with start_task(task="send_templated_message") as task: recipient_info = decode_recipient_info( msg.recipient_info, msg.sender or client_settings.default_sender) failed_transports = [] successful_transports = [] for transport_id, recipient in recipient_info.transports.items(): transport = TRANSPORTS[transport_id] await transport.connect() try: await transport.send_templated_message(msg, recipient, client_settings) except SendFailed: failed_transports.append(transport) else: successful_transports.append(transport) await transport.disconnect() msg_id = str(ULID()) task.add_success_fields( msg_id=msg_id, failed_transports=[t.transport_name for t in failed_transports], successful_transports=[ t.transport_name for t in successful_transports ]) if not successful_transports: transports_failed = TransportsFailed.ALL elif failed_transports: transports_failed = TransportsFailed.SOME else: transports_failed = TransportsFailed.NONE return MessageResponse(msg_id=msg_id, transports_failed=transports_failed)
def create_client(account_id, client): client['client_id'] = str(ULID()) client_item = { **make_indexes('Client', PK=f'CLIENT#{client["client_id"]}', SK=f'CLIENT#{client["client_id"]}'), **dict_to_item(client) } ddb_client.transact_write_items(TransactItems=[ make_put_unique(client_item), make_put_unique( dict_to_item( { 'PK': f'ACCOUNT#{account_id}#CLIENTEMAIL#{client["email"]}', 'SK': f'ACCOUNT#{account_id}#CLIENTEMAIL#{client["email"]}', }, False)), { 'Update': { 'TableName': table_name, 'Key': dict_to_item( { 'PK': f'ACCOUNT#{account_id}', 'SK': f'ACCOUNT#{account_id}', }, False), 'UpdateExpression': 'ADD Clients :clientId', 'ExpressionAttributeValues': dict_to_item({ ':clientId': set([client['client_id']]), }, False), } }, ]) return client['client_id']
def test_repr(): ulid = ULID() assert f"ULID({str(ulid)})" == repr(ulid)
def new_ulid_str(): return str(ULID())
from .extractor import Extractor from .manager import Manager from ulid import ULID id_generator = ULID()
def ulid(self): return ULID.from_str(self.id)
def test_ulid_from_timestamp(): t = time.time() ulid1 = ULID.from_timestamp(t) ulid2 = ULID.from_timestamp(int(t * constants.MILLISECS_IN_SECS)) assert ulid1.timestamp == ulid2.timestamp