dbos 0.6.0a3__py3-none-any.whl → 0.6.1__py3-none-any.whl

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.

Potentially problematic release.


This version of dbos might be problematic. Click here for more details.

dbos/__init__.py CHANGED
@@ -2,6 +2,7 @@ from . import error as error
2
2
  from .context import DBOSContextEnsure, SetWorkflowID
3
3
  from .dbos import DBOS, DBOSConfiguredInstance, WorkflowHandle, WorkflowStatus
4
4
  from .dbos_config import ConfigFile, get_dbos_database_url, load_config
5
+ from .kafka_message import KafkaMessage
5
6
  from .system_database import GetWorkflowsInput, WorkflowStatusString
6
7
 
7
8
  __all__ = [
@@ -10,6 +11,7 @@ __all__ = [
10
11
  "DBOSConfiguredInstance",
11
12
  "DBOSContextEnsure",
12
13
  "GetWorkflowsInput",
14
+ "KafkaMessage",
13
15
  "SetWorkflowID",
14
16
  "WorkflowHandle",
15
17
  "WorkflowStatus",
dbos/cli.py CHANGED
@@ -12,7 +12,7 @@ from typing import Any
12
12
  import tomlkit
13
13
  import typer
14
14
  from rich import print
15
- from rich.prompt import Confirm, Prompt
15
+ from rich.prompt import Prompt
16
16
  from typing_extensions import Annotated
17
17
 
18
18
  from dbos import load_config
@@ -30,6 +30,7 @@ def on_windows() -> bool:
30
30
  def start() -> None:
31
31
  config = load_config()
32
32
  start_commands = config["runtimeConfig"]["start"]
33
+ typer.echo("Executing start commands from 'dbos-config.yaml'")
33
34
  for command in start_commands:
34
35
  typer.echo(f"Executing: {command}")
35
36
 
@@ -129,9 +130,12 @@ def copy_template(src_dir: str, project_name: str, config_mode: bool) -> None:
129
130
  "project_name": project_name,
130
131
  "package_name": package_name,
131
132
  "db_name": db_name,
133
+ "migration_command": "alembic upgrade head",
132
134
  }
133
135
 
134
136
  if config_mode:
137
+ ctx["package_name"] = "."
138
+ ctx["migration_command"] = "echo 'No migrations specified'"
135
139
  copy_dbos_template(
136
140
  os.path.join(src_dir, "dbos-config.yaml.dbos"),
137
141
  os.path.join(dst_dir, "dbos-config.yaml"),
@@ -244,6 +248,7 @@ def migrate() -> None:
244
248
  app_db.destroy()
245
249
 
246
250
  # Next, run any custom migration commands specified in the configuration
251
+ typer.echo("Executing migration commands from 'dbos-config.yaml'")
247
252
  try:
248
253
  migrate_commands = (
249
254
  config["database"]["migrate"]
dbos/dbos.py CHANGED
@@ -54,11 +54,14 @@ from .tracer import dbos_tracer
54
54
 
55
55
  if TYPE_CHECKING:
56
56
  from fastapi import FastAPI
57
+ from dbos.kafka import KafkaConsumerWorkflow
57
58
  from .request import Request
58
59
  from flask import Flask
59
60
 
60
61
  from sqlalchemy.orm import Session
61
62
 
63
+ from dbos.request import Request
64
+
62
65
  if sys.version_info < (3, 10):
63
66
  from typing_extensions import ParamSpec, TypeAlias
64
67
  else:
@@ -506,6 +509,20 @@ class DBOS:
506
509
 
507
510
  return scheduled(_get_or_create_dbos_registry(), cron)
508
511
 
512
+ @classmethod
513
+ def kafka_consumer(
514
+ cls, config: dict[str, Any], topics: list[str]
515
+ ) -> Callable[[KafkaConsumerWorkflow], KafkaConsumerWorkflow]:
516
+ """Decorate a function to be used as a Kafka consumer."""
517
+ try:
518
+ from dbos.kafka import kafka_consumer
519
+
520
+ return kafka_consumer(_get_or_create_dbos_registry(), config, topics)
521
+ except ModuleNotFoundError as e:
522
+ raise DBOSException(
523
+ f"{e.name} dependency not found. Please install {e.name} via your package manager."
524
+ ) from e
525
+
509
526
  @classmethod
510
527
  def start_workflow(
511
528
  cls,
@@ -714,6 +731,12 @@ class DBOS:
714
731
  ctx = assert_current_dbos_context()
715
732
  return ctx.authenticated_roles
716
733
 
734
+ @classproperty
735
+ def assumed_role(cls) -> Optional[str]:
736
+ """Return the role currently assumed by the authenticated user, if any, associated with the current context."""
737
+ ctx = assert_current_dbos_context()
738
+ return ctx.assumed_role
739
+
717
740
  @classmethod
718
741
  def set_authentication(
719
742
  cls, authenticated_user: Optional[str], authenticated_roles: Optional[List[str]]
@@ -800,13 +823,9 @@ class DBOSConfiguredInstance:
800
823
 
801
824
  """
802
825
 
803
- def __init__(self, config_name: str, dbos: Optional[DBOS] = None) -> None:
826
+ def __init__(self, config_name: str) -> None:
804
827
  self.config_name = config_name
805
- if dbos is not None:
806
- assert isinstance(dbos, DBOS)
807
- dbos._registry.register_instance(self)
808
- else:
809
- DBOS.register_instance(self)
828
+ DBOS.register_instance(self)
810
829
 
811
830
 
812
831
  # Apps that import DBOS probably don't exit. If they do, let's see if
dbos/dbos_config.py CHANGED
@@ -2,7 +2,7 @@ import json
2
2
  import os
3
3
  import re
4
4
  from importlib import resources
5
- from typing import Dict, List, Optional, TypedDict
5
+ from typing import Any, Dict, List, Optional, TypedDict
6
6
 
7
7
  import yaml
8
8
  from jsonschema import ValidationError, validate
@@ -69,6 +69,7 @@ class ConfigFile(TypedDict, total=False):
69
69
  database: DatabaseConfig
70
70
  telemetry: Optional[TelemetryConfig]
71
71
  env: Dict[str, str]
72
+ application: Dict[str, Any]
72
73
 
73
74
 
74
75
  def substitute_env_vars(content: str) -> str:
dbos/kafka.py ADDED
@@ -0,0 +1,94 @@
1
+ import threading
2
+ import traceback
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING, Any, Callable, Generator, NoReturn, Optional, Union
5
+
6
+ from confluent_kafka import Consumer, KafkaError, KafkaException
7
+ from confluent_kafka import Message as CTypeMessage
8
+
9
+ if TYPE_CHECKING:
10
+ from dbos.dbos import _DBOSRegistry
11
+
12
+ from .context import SetWorkflowID
13
+ from .kafka_message import KafkaMessage
14
+ from .logger import dbos_logger
15
+
16
+ KafkaConsumerWorkflow = Callable[[KafkaMessage], None]
17
+
18
+
19
+ def _kafka_consumer_loop(
20
+ func: KafkaConsumerWorkflow,
21
+ config: dict[str, Any],
22
+ topics: list[str],
23
+ stop_event: threading.Event,
24
+ ) -> None:
25
+
26
+ def on_error(err: KafkaError) -> NoReturn:
27
+ raise KafkaException(err)
28
+
29
+ config["error_cb"] = on_error
30
+ if "auto.offset.reset" not in config:
31
+ config["auto.offset.reset"] = "earliest"
32
+
33
+ consumer = Consumer(config)
34
+ try:
35
+ consumer.subscribe(topics)
36
+ while not stop_event.is_set():
37
+ cmsg = consumer.poll(1.0)
38
+
39
+ if stop_event.is_set():
40
+ return
41
+
42
+ if cmsg is None:
43
+ continue
44
+
45
+ err = cmsg.error()
46
+ if err is not None:
47
+ dbos_logger.error(
48
+ f"Kafka error {err.code()} ({err.name()}): {err.str()}"
49
+ )
50
+ # fatal errors require an updated consumer instance
51
+ if err.code() == KafkaError._FATAL or err.fatal():
52
+ original_consumer = consumer
53
+ try:
54
+ consumer = Consumer(config)
55
+ consumer.subscribe(topics)
56
+ finally:
57
+ original_consumer.close()
58
+ else:
59
+ msg = KafkaMessage(
60
+ headers=cmsg.headers(),
61
+ key=cmsg.key(),
62
+ latency=cmsg.latency(),
63
+ leader_epoch=cmsg.leader_epoch(),
64
+ offset=cmsg.offset(),
65
+ partition=cmsg.partition(),
66
+ timestamp=cmsg.timestamp(),
67
+ topic=cmsg.topic(),
68
+ value=cmsg.value(),
69
+ )
70
+ with SetWorkflowID(
71
+ f"kafka-unique-id-{msg.topic}-{msg.partition}-{msg.offset}"
72
+ ):
73
+ try:
74
+ func(msg)
75
+ except Exception as e:
76
+ dbos_logger.error(
77
+ f"Exception encountered in Kafka consumer: {traceback.format_exc()}"
78
+ )
79
+
80
+ finally:
81
+ consumer.close()
82
+
83
+
84
+ def kafka_consumer(
85
+ dbosreg: "_DBOSRegistry", config: dict[str, Any], topics: list[str]
86
+ ) -> Callable[[KafkaConsumerWorkflow], KafkaConsumerWorkflow]:
87
+ def decorator(func: KafkaConsumerWorkflow) -> KafkaConsumerWorkflow:
88
+ stop_event = threading.Event()
89
+ dbosreg.register_poller(
90
+ stop_event, _kafka_consumer_loop, func, config, topics, stop_event
91
+ )
92
+ return func
93
+
94
+ return decorator
dbos/kafka_message.py ADDED
@@ -0,0 +1,15 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Union
3
+
4
+
5
+ @dataclass
6
+ class KafkaMessage:
7
+ headers: Optional[list[tuple[str, Union[str, bytes]]]]
8
+ key: Optional[Union[str, bytes]]
9
+ latency: Optional[float]
10
+ leader_epoch: Optional[int]
11
+ offset: Optional[int]
12
+ partition: Optional[int]
13
+ timestamp: tuple[int, int]
14
+ topic: Optional[str]
15
+ value: Optional[Union[str, bytes]]
@@ -15,7 +15,7 @@ database:
15
15
  password: ${PGPASSWORD}
16
16
  app_db_name: ${db_name}
17
17
  migrate:
18
- - alembic upgrade head
18
+ - ${migration_command}
19
19
  telemetry:
20
20
  logs:
21
21
  logLevel: INFO
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dbos
3
- Version: 0.6.0a3
3
+ Version: 0.6.1
4
4
  Summary: Ultra-lightweight durable execution in Python
5
5
  Author-Email: "DBOS, Inc." <contact@dbos.dev>
6
6
  License: MIT
@@ -91,7 +91,7 @@ def step_two():
91
91
  print("Step two completed!")
92
92
 
93
93
  @DBOS.workflow()
94
- def workflow():
94
+ def dbos_workflow():
95
95
  step_one()
96
96
  for _ in range(5):
97
97
  print("Press Control + \ to stop the app...")
@@ -99,8 +99,8 @@ def workflow():
99
99
  step_two()
100
100
 
101
101
  @app.get("/")
102
- def endpoint():
103
- workflow()
102
+ def fastapi_endpoint():
103
+ dbos_workflow()
104
104
  ```
105
105
 
106
106
  Save the program into `main.py`, edit `dbos-config.yaml` to configure your Postgres connection settings, and start it with `fastapi run`.
@@ -1,20 +1,22 @@
1
- dbos-0.6.0a3.dist-info/METADATA,sha256=6YdSITRGDjunFt92A4EPg9RDR__piiogGZ8NsEXYrKM,5000
2
- dbos-0.6.0a3.dist-info/WHEEL,sha256=rSwsxJWe3vzyR5HCwjWXQruDgschpei4h_giTm0dJVE,90
3
- dbos-0.6.0a3.dist-info/entry_points.txt,sha256=3PmOPbM4FYxEmggRRdJw0oAsiBzKR8U0yx7bmwUmMOM,39
4
- dbos-0.6.0a3.dist-info/licenses/LICENSE,sha256=VGZit_a5-kdw9WT6fY5jxAWVwGQzgLFyPWrcVVUhVNU,1067
5
- dbos/__init__.py,sha256=s3nYPf5yGR4XxiXS_JQbL8WVTjnnwr5EpFoCaCMrFxg,582
1
+ dbos-0.6.1.dist-info/METADATA,sha256=3WgP4NAQT1ZNQbEkLV9hupdBqevptUrwS2k6WpJ6dss,5016
2
+ dbos-0.6.1.dist-info/WHEEL,sha256=rSwsxJWe3vzyR5HCwjWXQruDgschpei4h_giTm0dJVE,90
3
+ dbos-0.6.1.dist-info/entry_points.txt,sha256=3PmOPbM4FYxEmggRRdJw0oAsiBzKR8U0yx7bmwUmMOM,39
4
+ dbos-0.6.1.dist-info/licenses/LICENSE,sha256=VGZit_a5-kdw9WT6fY5jxAWVwGQzgLFyPWrcVVUhVNU,1067
5
+ dbos/__init__.py,sha256=heuB3bqRXlVdfea9sKHBIVKSqFP6UuwhQecQfV4hyas,642
6
6
  dbos/admin_sever.py,sha256=Qg5T3YRrbPW05PR_99yAaxgo1ugQrAp_uTeTqSfjm_k,3397
7
7
  dbos/application_database.py,sha256=1K3kE96BgGi_QWOd2heXluyNTwFAwlUVuAR6JKKUqf0,5659
8
- dbos/cli.py,sha256=YARlQiWHUwFni-fEOr0k5P_-pqPS4xkywj_B0oTMXn0,8318
8
+ dbos/cli.py,sha256=z5dXbbnGWzSC3E1rfS8Lp1_OIImzcDKM7jP-iu_Q4aI,8602
9
9
  dbos/context.py,sha256=NVMGyvAa2RIiBVspvDz-8MBk_BQyGyYdPdorgO-GSng,16407
10
10
  dbos/core.py,sha256=jeqO8DABPAUrFlJXOfRfFDSnA8BGwiPnMa1JNbGuYLs,28584
11
11
  dbos/dbos-config.schema.json,sha256=azpfmoDZg7WfSy3kvIsk9iEiKB_-VZt03VEOoXJAkqE,5331
12
- dbos/dbos.py,sha256=zOTolY-lpDwpSO2ORrtIIRjIdi6JsQc9ovQDmvlc47I,28985
13
- dbos/dbos_config.py,sha256=SJ_UI4pHVKKjZDjge9Abm0HgcdQ6aDBO8QKBYujEPeE,5307
12
+ dbos/dbos.py,sha256=wzL51K7bY3J8grHXi0k0F0N09vFVBYWKwI0DGxyN4MY,29730
13
+ dbos/dbos_config.py,sha256=ih_TD_1zTKhPKxk8TPdEIp3ihu82R06SGKg-s4rHxws,5344
14
14
  dbos/decorators.py,sha256=lbPefsLK6Cya4cb7TrOcLglOpGT3pc6qjZdsQKlfZLg,629
15
15
  dbos/error.py,sha256=DDhB0VHmoZE_CP51ICdFMZSL2gmVS3Dm0aPNWncci94,3876
16
16
  dbos/fastapi.py,sha256=s7LnwwYVpJm_QZZwBW5um8NV2Q2Qx85uVZqGcKlSZAo,1881
17
17
  dbos/flask.py,sha256=azr4geMEGuuTBCyxIZmgDmmP-6s_pTIF-lGyp9Q4IB8,2430
18
+ dbos/kafka.py,sha256=FtngQHBu2TKfyDF7GFsKJAawFQJiOFxgKEUlNNxrdrw,3055
19
+ dbos/kafka_message.py,sha256=NYvOXNG3Qn7bghn1pv3fg4Pbs86ILZGcK4IB-MLUNu0,409
18
20
  dbos/logger.py,sha256=D-aFSZUCHBP34J1IZ5YNkTrJW-rDiH3py_v9jLU4Yrk,3565
19
21
  dbos/migrations/env.py,sha256=38SIGVbmn_VV2x2u1aHLcPOoWgZ84eCymf3g_NljmbU,1626
20
22
  dbos/migrations/script.py.mako,sha256=MEqL-2qATlST9TAOeYgscMn1uy6HUS9NFvDgl93dMj8,635
@@ -36,7 +38,7 @@ dbos/templates/hello/__package/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5
36
38
  dbos/templates/hello/__package/main.py,sha256=eI0SS9Nwj-fldtiuSzIlIG6dC91GXXwdRsoHxv6S_WI,2719
37
39
  dbos/templates/hello/__package/schema.py,sha256=7Z27JGC8yy7Z44cbVXIREYxtUhU4JVkLCp5Q7UahVQ0,260
38
40
  dbos/templates/hello/alembic.ini,sha256=VKBn4Gy8mMuCdY7Hip1jmo3wEUJ1VG1aW7EqY0_n-as,3695
39
- dbos/templates/hello/dbos-config.yaml.dbos,sha256=8wxCf_MIEFNWqMXj0nAHUwg1U3YaKz4xcUN6g51WkDE,603
41
+ dbos/templates/hello/dbos-config.yaml.dbos,sha256=X-Ocywo8_QUr2-Xj2AiiBYL0tcd0E3Yl7FuP6fy3gRM,603
40
42
  dbos/templates/hello/migrations/env.py.dbos,sha256=CsiFOea3ZIsahqkfYtioha0ewmlGR78Ng0wOB2t5LQg,2208
41
43
  dbos/templates/hello/migrations/script.py.mako,sha256=MEqL-2qATlST9TAOeYgscMn1uy6HUS9NFvDgl93dMj8,635
42
44
  dbos/templates/hello/migrations/versions/2024_07_31_180642_init.py,sha256=U5thFWGqNN4QLrNXT7wUUqftIFDNE5eSdqD8JNW1mec,942
@@ -44,4 +46,4 @@ dbos/templates/hello/start_postgres_docker.py,sha256=lQVLlYO5YkhGPEgPqwGc7Y8uDKs
44
46
  dbos/tracer.py,sha256=GaXDhdKKF_IQp5SAMipGXiDVwteRKjNbrXyYCH1mor0,2520
45
47
  dbos/utils.py,sha256=hWj9iWDrby2cVEhb0pG-IdnrxLqP64NhkaWUXiLc8bA,402
46
48
  version/__init__.py,sha256=L4sNxecRuqdtSFdpUGX3TtBi9KL3k7YsZVIvv-fv9-A,1678
47
- dbos-0.6.0a3.dist-info/RECORD,,
49
+ dbos-0.6.1.dist-info/RECORD,,
File without changes