Skip to content

Commit 63fbb43

Browse files
Add ctx.time() as wrapper around ctx.run(time.time) (#121)
1 parent c796ace commit 63fbb43

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

examples/random_greeter.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE
1010
#
1111
"""example.py"""
12+
from datetime import datetime
13+
1214
# pylint: disable=C0116
1315
# pylint: disable=W0613
1416

@@ -33,7 +35,21 @@ async def greet(ctx: Context, name: str) -> str:
3335
# As with ctx.random(), this won't write entries in the journal
3436
random_uuid = ctx.uuid()
3537

38+
# To get a timestamp, use ctx.time()
39+
# This will record the timestamp in the Restate journal
40+
now = await ctx.time()
41+
42+
# You can convert it to date/datetime using Python's standard library functions, e.g.
43+
now_datetime = datetime.fromtimestamp(now)
44+
45+
# Or to perform a difference:
46+
# start = await ctx.time()
47+
# # Some code
48+
# end = await ctx.time()
49+
# delta = datetime.timedelta(seconds=(end-start))
50+
3651
return (f"Hello {name} with "
3752
f"random number {random_number}, "
3853
f"random bytes {random_bytes!r} "
39-
f"and uuid {random_uuid}!")
54+
f"random uuid {random_uuid},"
55+
f"now datetime {now_datetime}!")

python/restate/context.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,14 @@ def uuid(self) -> UUID:
237237
This UUID will be stable across retries and replays.
238238
"""
239239

240+
@abc.abstractmethod
241+
def time(self) -> RestateDurableFuture[float]:
242+
"""
243+
Returns the result of time.time(), durably recorded in the journal.
244+
245+
This timestamp will be stable across retries and replays.
246+
"""
247+
240248
@typing_extensions.deprecated("`run` is deprecated, use `run_typed` instead for better type safety")
241249
@overload
242250
@abc.abstractmethod

python/restate/server_context.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import typing
2727
import traceback
2828
from uuid import UUID
29+
import time
2930

3031
from restate.context import DurablePromise, AttemptFinishedEvent, HandlerType, ObjectContext, Request, RestateDurableCallFuture, RestateDurableFuture, RunAction, SendHandle, RestateDurableSleepFuture, RunOptions, P
3132
from restate.exceptions import TerminalError
@@ -480,6 +481,9 @@ def random(self) -> Random:
480481
def uuid(self) -> UUID:
481482
return UUID(int=self.random_instance.getrandbits(128), version=4)
482483

484+
def time(self) -> RestateDurableFuture[float]:
485+
return self.run_typed("timestamp", time.time)
486+
483487
# pylint: disable=R0914
484488
async def create_run_coroutine(self,
485489
handle: int,

0 commit comments

Comments
 (0)