diff --git a/examples/random_greeter.py b/examples/random_greeter.py index cdb86ff..2cafbcb 100644 --- a/examples/random_greeter.py +++ b/examples/random_greeter.py @@ -9,6 +9,8 @@ # https://github.com/restatedev/sdk-typescript/blob/main/LICENSE # """example.py""" +from datetime import datetime + # pylint: disable=C0116 # pylint: disable=W0613 @@ -33,7 +35,21 @@ async def greet(ctx: Context, name: str) -> str: # As with ctx.random(), this won't write entries in the journal random_uuid = ctx.uuid() + # To get a timestamp, use ctx.time() + # This will record the timestamp in the Restate journal + now = await ctx.time() + + # You can convert it to date/datetime using Python's standard library functions, e.g. + now_datetime = datetime.fromtimestamp(now) + + # Or to perform a difference: + # start = await ctx.time() + # # Some code + # end = await ctx.time() + # delta = datetime.timedelta(seconds=(end-start)) + return (f"Hello {name} with " f"random number {random_number}, " f"random bytes {random_bytes!r} " - f"and uuid {random_uuid}!") + f"random uuid {random_uuid}," + f"now datetime {now_datetime}!") diff --git a/python/restate/context.py b/python/restate/context.py index f006097..3681072 100644 --- a/python/restate/context.py +++ b/python/restate/context.py @@ -237,6 +237,14 @@ def uuid(self) -> UUID: This UUID will be stable across retries and replays. """ + @abc.abstractmethod + def time(self) -> RestateDurableFuture[float]: + """ + Returns the result of time.time(), durably recorded in the journal. + + This timestamp will be stable across retries and replays. + """ + @typing_extensions.deprecated("`run` is deprecated, use `run_typed` instead for better type safety") @overload @abc.abstractmethod diff --git a/python/restate/server_context.py b/python/restate/server_context.py index 259e612..ae2582f 100644 --- a/python/restate/server_context.py +++ b/python/restate/server_context.py @@ -26,6 +26,7 @@ import typing import traceback from uuid import UUID +import time from restate.context import DurablePromise, AttemptFinishedEvent, HandlerType, ObjectContext, Request, RestateDurableCallFuture, RestateDurableFuture, RunAction, SendHandle, RestateDurableSleepFuture, RunOptions, P from restate.exceptions import TerminalError @@ -480,6 +481,9 @@ def random(self) -> Random: def uuid(self) -> UUID: return UUID(int=self.random_instance.getrandbits(128), version=4) + def time(self) -> RestateDurableFuture[float]: + return self.run_typed("timestamp", time.time) + # pylint: disable=R0914 async def create_run_coroutine(self, handle: int,