Skip to content

Commit

Permalink
Move events to common (#8676)
Browse files Browse the repository at this point in the history
* Move events to common

* More Type Annotations (#8536)

* Extend use of type annotations in the events module.

* Add return type of None to more __init__ definitions.

* Still more type annotations adding -> None to __init__

* Tweak per review

* Allow adapters to include python package logging in dbt logs (#8643)

* add set_package_log_level functionality

* set package handler

* set package handler

* add logging about stting up logging

* test event log handler

* add event log handler

* add event log level

* rename package and add unit tests

* revert logfile config change

* cleanup and add code comments

* add changie

* swap function for dict

* add additional unit tests

* fix unit test

* update README and protos

* fix formatting

* update precommit

---------

Co-authored-by: Peter Webb <peter.webb@dbtlabs.com>
  • Loading branch information
2 people authored and MichelleArk committed Oct 25, 2023
1 parent 469a9ac commit c141148
Show file tree
Hide file tree
Showing 94 changed files with 1,226 additions and 205 deletions.
6 changes: 6 additions & 0 deletions .changes/unreleased/Features-20230915-123733.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
kind: Features
body: 'Allow adapters to include package logs in dbt standard logging '
time: 2023-09-15T12:37:33.862862-07:00
custom:
Author: colin-rogers-dbt
Issue: "7859"
6 changes: 6 additions & 0 deletions .changes/unreleased/Under the Hood-20230831-164435.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
kind: Under the Hood
body: Added more type annotations.
time: 2023-08-31T16:44:35.737954-04:00
custom:
Author: peterallenwebb
Issue: "8537"
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Configuration for pre-commit hooks (see https://pre-commit.com/).
# Eventually the hooks described here will be run as tests before merging each PR.

exclude: ^(core/dbt/docs/build/|core/dbt/events/types_pb2.py)
exclude: ^(core/dbt/docs/build/|core/dbt/common/events/types_pb2.py)

# Force all unspecified python hooks to run python 3.8
default_language_version:
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ dev: dev_req ## Installs dbt-* packages in develop mode along with development d

.PHONY: proto_types
proto_types: ## generates google protobuf python file from types.proto
protoc -I=./core/dbt/events --python_out=./core/dbt/events ./core/dbt/events/types.proto
protoc -I=./core/dbt/common/events --python_out=./core/dbt/common/events ./core/dbt/common/events/types.proto

.PHONY: mypy
mypy: .env ## Runs mypy against staged changes for static type checking.
Expand Down
8 changes: 4 additions & 4 deletions core/dbt/adapters/base/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@
from dbt.adapters.base.query_headers import (
MacroQueryStringSetter,
)
from dbt.events import AdapterLogger
from dbt.events.functions import fire_event
from dbt.events.types import (
from dbt.common.events import AdapterLogger
from dbt.common.events.functions import fire_event
from dbt.common.events.types import (
NewConnection,
ConnectionReused,
ConnectionLeftOpenInCleanup,
Expand All @@ -48,7 +48,7 @@
Rollback,
RollbackFailed,
)
from dbt.events.contextvars import get_node_info
from dbt.common.events.contextvars import get_node_info
from dbt import flags
from dbt.utils import cast_to_str

Expand Down
4 changes: 2 additions & 2 deletions core/dbt/adapters/base/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@
from dbt.clients.jinja import MacroGenerator
from dbt.contracts.graph.manifest import Manifest, MacroManifest
from dbt.contracts.graph.nodes import ResultNode
from dbt.events.functions import fire_event, warn_or_error
from dbt.events.types import (
from dbt.common.events.functions import fire_event, warn_or_error
from dbt.common.events.types import (
CacheMiss,
ListRelations,
CodeExecution,
Expand Down
4 changes: 2 additions & 2 deletions core/dbt/adapters/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
ReferencedLinkNotCachedError,
TruncatedModelNameCausedCollisionError,
)
from dbt.events.functions import fire_event, fire_event_if
from dbt.events.types import CacheAction, CacheDumpGraph
from dbt.common.events.functions import fire_event, fire_event_if
from dbt.common.events.types import CacheAction, CacheDumpGraph
from dbt.flags import get_flags
from dbt.utils import lowercase

Expand Down
8 changes: 4 additions & 4 deletions core/dbt/adapters/contracts/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@
from dbt.common.contracts.util import Replaceable
from dbt.common.util import md5

# TODO: dbt.events dependency
from dbt.events.functions import fire_event
from dbt.events.types import NewConnectionOpening
# TODO: dbt.common.events dependency
from dbt.common.events.functions import fire_event
from dbt.common.events.types import NewConnectionOpening

# TODO: this is a very bad dependency - shared global state
from dbt.events.contextvars import get_node_info
from dbt.common.events.contextvars import get_node_info


class Identifier(ValidatedStringMixin):
Expand Down
4 changes: 2 additions & 2 deletions core/dbt/adapters/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
from dbt.adapters.base.plugin import AdapterPlugin
from dbt.adapters.protocol import AdapterConfig, AdapterProtocol, RelationProtocol
from dbt.adapters.contracts.connection import AdapterRequiredConfig, Credentials
from dbt.events.functions import fire_event
from dbt.events.types import AdapterImportError, PluginLoadError, AdapterRegistered
from dbt.common.events.functions import fire_event
from dbt.common.events.types import AdapterImportError, PluginLoadError, AdapterRegistered
from dbt.exceptions import DbtInternalError, DbtRuntimeError
from dbt.include.global_project import PACKAGE_PATH as GLOBAL_PROJECT_PATH
from dbt.include.global_project import PROJECT_NAME as GLOBAL_PROJECT_NAME
Expand Down
6 changes: 3 additions & 3 deletions core/dbt/adapters/sql/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
import dbt.exceptions
from dbt.adapters.base import BaseConnectionManager
from dbt.adapters.contracts.connection import Connection, ConnectionState, AdapterResponse
from dbt.events.functions import fire_event
from dbt.events.types import ConnectionUsed, SQLQuery, SQLCommit, SQLQueryStatus
from dbt.events.contextvars import get_node_info
from dbt.common.events.functions import fire_event
from dbt.common.events.types import ConnectionUsed, SQLQuery, SQLCommit, SQLQueryStatus
from dbt.common.events.contextvars import get_node_info
from dbt.utils import cast_to_str


Expand Down
4 changes: 2 additions & 2 deletions core/dbt/adapters/sql/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from dbt.adapters.base import BaseAdapter, available
from dbt.adapters.cache import _make_ref_key_dict
from dbt.adapters.sql import SQLConnectionManager
from dbt.events.functions import fire_event
from dbt.events.types import ColTypeChange, SchemaCreation, SchemaDrop
from dbt.common.events.functions import fire_event
from dbt.common.events.types import ColTypeChange, SchemaCreation, SchemaDrop


from dbt.adapters.base.relation import BaseRelation
Expand Down
2 changes: 1 addition & 1 deletion core/dbt/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
CatalogArtifact,
RunExecutionResult,
)
from dbt.events.base_types import EventMsg
from dbt.common.events.base_types import EventMsg
from dbt.task.build import BuildTask
from dbt.task.clean import CleanTask
from dbt.task.clone import CloneTask
Expand Down
16 changes: 11 additions & 5 deletions core/dbt/cli/requires.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,23 @@
from dbt.cli.flags import Flags
from dbt.config import RuntimeConfig
from dbt.config.runtime import load_project, load_profile, UnsetProfile
from dbt.events.base_types import EventLevel
from dbt.events.functions import fire_event, LOG_VERSION, set_invocation_id, setup_event_logger
from dbt.events.types import (

from dbt.common.events.base_types import EventLevel
from dbt.common.events.functions import (
fire_event,
LOG_VERSION,
set_invocation_id,
setup_event_logger,
)
from dbt.common.events.types import (
CommandCompleted,
MainReportVersion,
MainReportArgs,
MainTrackingUserState,
ResourceReport,
)
from dbt.events.helpers import get_json_string_utcnow
from dbt.events.types import MainEncounteredError, MainStackTrace
from dbt.common.events.helpers import get_json_string_utcnow
from dbt.common.events.types import MainEncounteredError, MainStackTrace
from dbt.exceptions import Exception as DbtException, DbtProjectError, FailFastError
from dbt.parser.manifest import ManifestLoader, write_manifest
from dbt.profiler import profiler
Expand Down
4 changes: 2 additions & 2 deletions core/dbt/clients/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import os.path

from dbt.clients.system import run_cmd, rmdir
from dbt.events.functions import fire_event
from dbt.events.types import (
from dbt.common.events.functions import fire_event
from dbt.common.events.types import (
GitSparseCheckoutSubdirectory,
GitProgressCheckoutRevision,
GitProgressUpdatingExistingDependency,
Expand Down
4 changes: 2 additions & 2 deletions core/dbt/clients/registry.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import functools
from typing import Any, Dict, List
import requests
from dbt.events.functions import fire_event
from dbt.events.types import (
from dbt.common.events.functions import fire_event
from dbt.common.events.types import (
RegistryProgressGETRequest,
RegistryProgressGETResponse,
RegistryIndexProgressGETRequest,
Expand Down
4 changes: 2 additions & 2 deletions core/dbt/clients/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@

import dbt.exceptions
import requests
from dbt.events.functions import fire_event
from dbt.events.types import (
from dbt.common.events.functions import fire_event
from dbt.common.events.types import (
SystemCouldNotWrite,
SystemExecutingCmd,
SystemStdOut,
Expand Down
Empty file added core/dbt/common/__init__.py
Empty file.
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ from dbt.logger import GLOBAL_LOGGER as logger

Simply change it to these two lines with your adapter's database name, and all your existing call sites will now use the new system for v1.0:
```python
from dbt.events import AdapterLogger
from dbt.common.events import AdapterLogger
logger = AdapterLogger("<database name>")
# e.g. AdapterLogger("Snowflake")
```
Expand All @@ -52,4 +52,4 @@ logger = AdapterLogger("<database name>")

After adding a new message in `types.proto`, either:
- In the repository root directory: `make proto_types`
- In the `core/dbt/events` directory: `protoc -I=. --python_out=. types.proto`
- In the `core/dbt/common/events` directory: `protoc -I=. --python_out=. types.proto`
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import traceback
from dataclasses import dataclass
from dbt.events.functions import fire_event, EVENT_MANAGER
from dbt.events.contextvars import get_node_info
from dbt.events.event_handler import set_package_logging
from dbt.events.types import (

from dbt.common.events.event_handler import set_package_logging
from dbt.common.events.functions import fire_event, EVENT_MANAGER
from dbt.common.events.contextvars import get_node_info
from dbt.common.events.types import (
AdapterEventDebug,
AdapterEventInfo,
AdapterEventWarning,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from enum import Enum
import os
import threading
from dbt.events import types_pb2
from dbt.common.events import types_pb2
import sys
from google.protobuf.json_format import ParseDict, MessageToDict, MessageToJson
from google.protobuf.message import Message
from dbt.events.helpers import get_json_string_utcnow
from dbt.common.events.helpers import get_json_string_utcnow
from typing import Optional

if sys.version_info >= (3, 8):
Expand All @@ -21,13 +21,13 @@


def get_global_metadata_vars() -> dict:
from dbt.events.functions import get_metadata_vars
from dbt.common.events.functions import get_metadata_vars

return get_metadata_vars()


def get_invocation_id() -> str:
from dbt.events.functions import get_invocation_id
from dbt.common.events.functions import get_invocation_id

return get_invocation_id()

Expand Down Expand Up @@ -72,8 +72,8 @@ def __init__(self, *args, **kwargs) -> None:
self.pb_msg = ParseDict(kwargs, msg_cls())
except Exception:
# Imports need to be here to avoid circular imports
from dbt.events.types import Note
from dbt.events.functions import fire_event
from dbt.common.events.types import Note
from dbt.common.events.functions import fire_event

error_msg = f"[{class_name}]: Unable to parse dict {kwargs}"
# If we're testing throw an error so that we notice failures
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import logging
from typing import Union

from dbt.events.base_types import EventLevel
from dbt.events.types import Note
from dbt.common.events.base_types import EventLevel
from dbt.common.events.types import Note
from dbt.common.events.eventmgr import IEventManager

from dbt.events.eventmgr import IEventManager

_log_level_to_event_level_map = {
logging.DEBUG: EventLevel.DEBUG,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from typing import Callable, List, Optional, Protocol, Tuple
from uuid import uuid4

from dbt.events.base_types import BaseEvent, EventLevel, msg_from_base_event, EventMsg
from dbt.events.logger import LoggerConfig, _Logger, _TextLogger, _JsonLogger, LineFormat
from dbt.common.events.base_types import BaseEvent, EventLevel, msg_from_base_event, EventMsg
from dbt.common.events.logger import LoggerConfig, _Logger, _TextLogger, _JsonLogger, LineFormat


class EventManager:
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from dbt.constants import METADATA_ENV_PREFIX
from dbt.events.base_types import BaseEvent, EventLevel, EventMsg
from dbt.events.eventmgr import EventManager, IEventManager
from dbt.events.logger import LoggerConfig, NoFilter, LineFormat
from dbt.common.events.base_types import BaseEvent, EventLevel, EventMsg
from dbt.common.events.eventmgr import EventManager, IEventManager
from dbt.common.events.logger import LoggerConfig, NoFilter, LineFormat
from dbt.exceptions import scrub_secrets, env_secrets
from dbt.events.types import Note
from dbt.common.events.types import Note
from dbt.flags import get_flags, ENABLE_LEGACY_LOGGER
from dbt.logger import GLOBAL_LOGGER, make_log_dir_if_missing
from functools import partial
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
from colorama import Style

import dbt.utils
from dbt.events.base_types import EventLevel, EventMsg
from dbt.events.format import timestamp_to_datetime_string
from dbt.common.events.base_types import EventLevel, EventMsg
from dbt.common.events.format import timestamp_to_datetime_string

# A Filter is a function which takes a BaseEvent and returns True if the event
# should be logged, False otherwise.
Expand Down Expand Up @@ -172,7 +172,7 @@ def _get_thread_name(self) -> str:

class _JsonLogger(_Logger):
def create_line(self, msg: EventMsg) -> str:
from dbt.events.functions import msg_to_dict
from dbt.common.events.functions import msg_to_dict

Check warning on line 175 in core/dbt/common/events/logger.py

View check run for this annotation

Codecov / codecov/patch

core/dbt/common/events/logger.py#L175

Added line #L175 was not covered by tests

msg_dict = msg_to_dict(msg)
raw_log_line = json.dumps(msg_dict, sort_keys=True, cls=dbt.utils.ForgivingJSONEncoder)
Expand Down
File renamed without changes.
8 changes: 6 additions & 2 deletions core/dbt/events/types.py → core/dbt/common/events/types.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import json

from dbt.constants import MAXIMUM_SEED_SIZE_NAME, PIN_PACKAGE_URL
from dbt.events.base_types import (
from dbt.common.events.base_types import (
DynamicLevel,
DebugLevel,
InfoLevel,
WarnLevel,
ErrorLevel,
EventLevel,
)
from dbt.events.format import format_fancy_output_line, pluralize, timestamp_to_datetime_string
from dbt.common.events.format import (
format_fancy_output_line,
pluralize,
timestamp_to_datetime_string,
)
from dbt.node_types import NodeType
from dbt.ui import line_wrap_message, warning_tag, red, green, yellow

Expand Down
938 changes: 938 additions & 0 deletions core/dbt/common/events/types_pb2.py

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions core/dbt/compilation.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@
DbtRuntimeError,
)
from dbt.graph import Graph
from dbt.events.functions import fire_event, get_invocation_id
from dbt.events.types import FoundStats, Note, WritingInjectedSQLForNode
from dbt.events.contextvars import get_node_info
from dbt.common.events.functions import fire_event, get_invocation_id
from dbt.common.events.types import FoundStats, Note, WritingInjectedSQLForNode
from dbt.common.events.contextvars import get_node_info
from dbt.node_types import NodeType, ModelLanguage
from dbt.events.format import pluralize
from dbt.common.events.format import pluralize
import dbt.tracking
import dbt.task.list as list_task
import sqlparse
Expand Down
4 changes: 2 additions & 2 deletions core/dbt/config/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
DbtRuntimeError,
ProfileConfigError,
)
from dbt.events.types import MissingProfileTarget
from dbt.events.functions import fire_event
from dbt.common.events.types import MissingProfileTarget
from dbt.common.events.functions import fire_event
from dbt.utils import coerce_dict_str

from .renderer import ProfileRenderer
Expand Down
4 changes: 2 additions & 2 deletions core/dbt/config/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
from dbt.contracts.project import Configuration, UserConfig
from dbt.contracts.relation import ComponentName
from dbt.common.dataclass_schema import ValidationError
from dbt.events.functions import warn_or_error
from dbt.events.types import UnusedResourceConfigPath
from dbt.common.events.functions import warn_or_error
from dbt.common.events.types import UnusedResourceConfigPath
from dbt.exceptions import (
ConfigContractBrokenError,
DbtProjectError,
Expand Down
4 changes: 2 additions & 2 deletions core/dbt/config/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@


from dbt.clients import yaml_helper
from dbt.events.functions import fire_event
from dbt.events.types import InvalidOptionYAML
from dbt.common.events.functions import fire_event
from dbt.common.events.types import InvalidOptionYAML
from dbt.exceptions import DbtValidationError, OptionNotYamlDictError


Expand Down
Loading

0 comments on commit c141148

Please sign in to comment.