Cosmos Hub 백서

Cosmos Hub

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 8쪽

interfaces, types and abstractions for Cosmos SDK modules to read and write to Merkleized state within a Cosmos SDK application. The store package provides many primitives for developers to use in order to work with both state storage and state commitment. Below we describe the various abstractions. ## Types ### `Store` The bulk of the store interfaces are defined [here](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/types/store.go), where the base primitive interface, for which other interfaces build off of, is the `Store` type. The `Store` interface defines the ability to tell the type of the implementing store and the ability to cache wrap via the `CacheWrapper` interface. ### `CacheWrapper` & `CacheWrap` One of the most important features a store has the ability to perform is the ability to cache wrap. Cache wrapping is essentially the underlying store wrapping itself within another store type that performs caching for both reads and writes with the ability to flush writes via `Write()`. ### `KVStore` & `CacheKVStore` One of the most important interfaces that both developers and modules interface with, which also provides the basis of most state storage and commitment operations, is the `KVStore`. The `KVStore` interface provides basic CRUD abilities and prefix-based iteration, including reverse iteration. Typically, each module has its own dedicated `KVStore` instance, which it can get access to via the `sdk.Context` and the use of a pointer-based named key -- `KVStoreKey`. The `KVStoreKey` provides pseudo-OCAP. How exactly a `KVStoreKey` maps to a `KVStore` will be illustrated below through the `CommitMultiStore`. Note, a `KVStore` cannot directly commit state. Instead, a `KVStore` can be wrapped by a `CacheKVStore` which extends a `KVStore` and provides the ability for the caller to execute `Write()` which flushes pending writes to the parent `KVStore` in memory. Note, this doesn't actually flush writes to disk as writes are held in memory until `Commit()` is called on the `CommitMultiStore`. ### `CommitMultiStore` The `CommitMultiStore` interface exposes the top-level interface that is used to manage state commitment and storage by an SDK application and abstracts the concept of multiple `KVStore`s which are used by multiple modules. Specifically, it supports the following high-level primitives: * Allows for a caller to retrieve a `KVStore` by providing a `KVStoreKey`. * Exposes pruning mechanisms to remove state pinned against a specific height/version in the past. * Allows for loading state storage at a particular height/version in the past to provide current head and historical queries. * Provides the ability to rollback state to a previous height/version. * Provides the ability to load state storage at a particular height/version while also performing store upgrades, which are used during live hard-fork application state migrations. * Provides the ability to commit all current accumulated state to disk and performs Merkle commitment. ## Implementation Details While there are many interfaces that the `store` package provides, there is typically a core implementation for each main interface that modules and developers interact with that are defined in the Cosmos SDK. ### `iavl.Store` The `iavl.Store` provides the core implementation for state storage and commitment by implementing the following interfaces: * `KVStore` * `CommitStore` * `CommitKVStore` * `Queryable` * `StoreWithInitialVersion` It allows for all CRUD operations to be performed along with allowing current and historical state queries, prefix iteration, and state commitment along with Merkle proof operations. The `iavl.Store` also provides the ability to remove historical state from the state commitment layer. An overview of the IAVL implementation can be found [here](https://github.com/cosmos/iavl/blob/master/docs/overview.md). It is important to note that the IAVL store provides both state commitment and logical storage operations, which comes with drawbacks as there are various performance impacts, some of which are very drastic, when it comes to the operations mentioned above. When dealing with state management in modules and clients, the Cosmos SDK provides various layers of abstractions or "store wrapping", where the `iavl.Store` is the bottom most layer. When requesting a store to perform reads or writes in a module, the typical abstraction layer in order is defined as follows: ```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} rootmulti.Store -> cachemulti.Store -> gaskv.Store -> cachekv.Store -> iavl.Store ``` ### Concurrent use of IAVL store The tree under `iavl.Store` is not safe for concurrent use. It is the responsibility of the caller to ensure that concurrent access to the store is not performed. The main issue with concurrent use is when data is written at the same time as it's being iterated over. Doing so will cause an irrecoverable fatal error because of concurrent reads and writes to an internal map. Although it's not recommended, you can iterate through values while writing to it by disabling "FastNode" **without guarantees that the values being written will be returned during the iteration** (if you need this, you might want to reconsider the design of your application). This is done by setting `iavl-disable-fastnode` to `true` in the config TOML file. ### `cachekv.Store` The `cachekv.Store` store wraps an underlying `KVStore`, typically a `iavl.Store` and contains an in-memory cache for storing pending writes to underlying `KVStore`. `Set` and `Delete` calls are executed on the in-memory cache. `Has` checks the cache first, falling through to the underlying `KVStore` only on a cache miss. One of the most important calls to a `cachekv.Store` is `Write()`, which ensures that key-value pairs are written to the underlying `KVStore` in a deterministic and ordered manner by sorting the keys first. The store keeps track of "dirty" keys and uses these to determine what keys to sort. Deletions are represented as zero-value (nil) entries; `Write()` detects these and calls `Delete` on the underlying `KVStore` for each one. The `cachekv.Store` also provides the ability to perform iteration and reverse iteration. Iteration is performed through the `cacheMergeIterator` type and uses both the dirty cache and underlying `KVStore` to iterate over key-value pairs. Note, all calls to CRUD and iteration operations on a `cachekv.Store` are thread-safe. ### `gaskv.Store` The `gaskv.Store` store provides a simple implementation of a `KVStore`. Specifically, it just wraps an existing `KVStore`, such as a cache-wrapped `iavl.Store`, and incurs configurable gas costs for CRUD operations via `ConsumeGas()` calls on a `GasMeter` passed at construction time, then proxies the underlying CRUD call to the wrapped store. ### `cachemulti.Store` & `rootmulti.Store` The `rootmulti.Store` acts as an abstraction around a series of stores. Namely, it implements the `CommitMultiStore` an `Queryable` interfaces. Through the `rootmulti.Store`, an SDK module can request access to a `KVStore` to perform state CRUD operations and queries by holding access to a unique `KVStoreKey`. The `rootmulti.Store` ensures these queries and state operations are performed through cached-wrapped instances of `cachekv.Store` which is described above. The `rootmulti.Store` implementation is also responsible for committing all accumulated state from each `KVStore` to disk and returning an application state Merkle root. Queries can be performed to return state data along with associated state commitment proofs for both previous heights/versions and the current state root. Queries are routed based on store name, i.e. a module, along with other parameters defined in the SDK's `RequestQuery` type. The `rootmulti.Store` also provides primitives for pruning data at a given height/version from state storage. When a height is committed, the `rootmulti.Store` will determine if other previous heights should be considered for removal based on the operator's pruning settings defined by `PruningOptions`, which defines how many recent versions to keep on disk and the interval at which to remove "staged" pruned heights from disk. During each interval, the staged heights are removed from each `KVStore`. Note, it is up to the underlying `KVStore` implementation to determine how pruning is actually performed. The `PruningOptions` are defined as follows: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type PruningOptions struct { // KeepRecent defines how many recent heights to keep on disk. KeepRecent uint64 // Interval defines when the pruned heights are removed from disk. Interval uint64 // Strategy defines the kind of pruning strategy. See below for more information on each. Strategy PruningStrategy } ``` The Cosmos SDK defines a preset number of pruning "strategies": `default`, `everything`, `nothing`, and `custom`. It is important to note that the `rootmulti.Store` considers each `KVStore` as a separate logical store. In other words, they do not share a Merkle tree or comparable data structure. This means that when state is committed via `rootmulti.Store`, each store is committed in sequence and thus is not atomic. In terms of store construction and wiring, each Cosmos SDK application contains a `BaseApp` instance which internally has a reference to a `CommitMultiStore` that is implemented by a `rootmulti.Store`. The application then registers one or more `KVStoreKey` that pertain to a unique module and thus a `KVStore`. Through the use of an `sdk.Context` and a `KVStoreKey`, each module can get direct access to it's respective `KVStore` instance. Example: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func NewApp(...) Application { // ... bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseAppOptions...) bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) // ... keys := sdk.NewKVStoreKeys(...) transientKeys := sdk.NewTransientStoreKeys(...) memKeys := sdk.NewMemoryStoreKeys(...) // ... // initialize stores app.MountKVStores(keys) app.MountTransientStores(transientKeys) app.MountMemoryStores(memKeys) // ... } ``` The `rootmulti.Store` itself can be cache-wrapped which returns an instance of a `cachemulti.Store`. For each block, `BaseApp` ensures that the proper abstractions are created on the `CommitMultiStore`, i.e. ensuring that the `rootmulti.Store` is cached-wrapped and uses the resulting `cachemulti.Store` to be set on the `sdk.Context` which is then used for block and transaction execution. As a result, all state mutations due to block and transaction execution are actually held ephemerally until `Commit()` is called by the ABCI client. This concept is further expanded upon when the AnteHandler is executed per transaction to ensure state is not committed for transactions that failed CheckTx. # Log v2 Source: https://docs.cosmos.network/sdk/latest/guides/testing/log `cosmossdk.io/log/v2` is the Cosmos SDK logging package. At a high level, there are three pieces to understand: 1. `log.NewLogger(...)` creates the default Cosmos SDK logger. It is backed by `zerolog`. 2. `cosmossdk.io/log/v2/slog` lets you satisfy the same SDK `Logger` interface with a standard library `*slog.Logger`. 3. `log.NewMultiLogger(...)` fans one log call out to multiple SDK loggers. The SDK uses this during server startup when OpenTelemetry log exporting is enabled. To learn more about how we support OpenTelemetry, read the [Telemetry docs](/sdk/latest/guides/testing/telemetry). If you only need ordinary SDK logging, you usually only need `log.NewLogger`, which is automatically provisioned and set on `sdk.Context`. ## Default Logger The default implementation is a small wrapper around `zerolog`. ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} logger := log.NewLogger(os.Stderr) logger.Info("starting app", "chain_id", chainID) logger.Error("failed to load state", "err", err) ``` `NewLogger` writes human-readable console output by default. The server command wiring switches options based on CLI configuration, for example: * `OutputJSONOption()` for JSON logs * `LevelOption(...)` for a global log level * `FilterOption(...)` for module-based filtering * `TraceOption(true)` to include stack traces on error logs * `VerboseLevelOption(...)` for temporary verbose mode The SDK also uses the `module` field consistently. The package exposes `log.ModuleKey` for this: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} logger = logger.With(log.ModuleKey, "bank") logger.Info("send coins", "from", from, "to", to) ``` That matters because the log filter implementation keys off the `module` field when parsing values such as `consensus:debug,*:error`. ## Structured Context `Logger.With(...)` returns a derived logger with additional fields: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} keeperLogger := logger.With(log.ModuleKey, "staking", "component", "keeper") keeperLogger.Info("validator updated", "operator", valAddr) ``` This is the normal way to attach stable metadata to a logger instance. ## Context-Aware Logging The v2 `Logger` interface adds `*Context` methods: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type Logger interface { Info(msg string, keyVals ...any) InfoContext(ctx context.Context, msg string, keyVals ...any) Warn(msg string, keyVals ...any) WarnContext(ctx context.Context, msg string, keyVals ...any) Error(msg string, keyVals ...any) ErrorContext(ctx context.Context, msg string, keyVals ...any) Debug(msg string, keyVals ...any) DebugContext(ctx context.Context, msg string, keyVals ...any) With(keyVals ...any) Logger Impl() any } ``` The important distinction is: * `Info`, `Warn`, `Error`, and `Debug` log without inspecting a `context.Context` * `InfoContext`, `WarnContext`, `ErrorContext`, and `DebugContext` use the provided context for trace correlation For the default `zerolog` implementation, the `*Context` methods extract the active OpenTelemetry span from `ctx` and add: * `trace_id` * `span_id` * `trace_flags` when present If there is no valid span in the context, they behave like normal log calls. ## Trace Correlation When you want logs to line up with spans, use the context-aware methods. ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (k Keeper) UpdateBalance(ctx sdk.Context, addr sdk.AccAddress, coins sdk.Coins) error { ctx, span := ctx.StartSpan(tracer, "UpdateBalance") defer span.End() logger := ctx.Logger().With(log.ModuleKey, "bank") logger.InfoContext(ctx, "updating balance", "address", addr.String()) return nil } ``` Two details matter here: 1. `sdk.Context.StartSpan(...)` returns a new `sdk.Context` with the Go `context.Context` updated to include the span. 2. The logger only sees trace information when you call one of the logger's `*Context` methods with that updated context. Without the `*Context` call, the default logger will not add trace fields to the log record. ## `log/slog` `cosmossdk.io/log/v2/slog` is an adapter for code that already has a standard library `*slog.Logger`. ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} base := slog.New(handler) logger := sdklogSlog.NewCustomLogger(base) ``` This does not add extra SDK behavior by itself. It simply makes a `*slog.Logger` satisfy the Cosmos SDK `Logger` interface. Filtering, formatting, sinks, and handler behavior are whatever the underlying `slog.Logger` is configured to do. ## `MultiLogger` `log.NewMultiLogger(loggers...)` returns a logger that dispatches each log call to every wrapped logger. That includes: * ordinary log methods such as `Info(...)` * context-aware methods such as `InfoContext(...)` * `With(...)`, which derives a child logger for each wrapped logger If an underlying logger implements `VerboseModeLogger`, `SetVerboseMode(...)` is also forwarded. In other words, `MultiLogger` is just fanout. It does not merge records or add new fields on its own. ## When The SDK Configures `MultiLogger` `MultiLogger` is not created for every app automatically. During the node's server start, the SDK first builds the normal server logger from CLI/config flags. That logger is the usual `zerolog`-backed logger. Then the SDK initializes OpenTelemetry from `config/otel.yaml`. If `telemetry.IsOtelLoggerEnabled()` reports that the global OpenTelemetry logger provider has active log processors/exporters, the SDK wraps the existing server logger like this: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} otelLogger := sdkSlog.NewCustomLogger(otelslog.NewLogger("")) svrCtx.Logger = log.NewMultiLogger(svrCtx.Logger, otelLogger) ``` So when OpenTelemetry log exporting is enabled, one log call is sent to: * the existing console/stdout logger * an OpenTelemetry-backed logger for export If OpenTelemetry logging is not enabled, the server continues using only the normal logger. ## What `otelslog` Is `otelslog` is an OpenTelemetry bridge for Go's `log/slog` package. More specifically, it provides a `slog.Handler` and `slog.Logger` that convert `slog.Record` values into OpenTelemetry log records and sends them to the configured OpenTelemetry logger provider. In the Cosmos SDK startup path: * `otelslog.NewLogger("")` creates an `*slog.Logger` backed by that bridge * `cosmossdk.io/log/v2/slog.NewCustomLogger(...)` wraps it so it satisfies the SDK `Logger` interface * `log.NewMultiLogger(...)` fans logs out to both the normal `zerolog` logger and the OpenTelemetry bridge Because `slog` has native `InfoContext`/`WarnContext`/`ErrorContext`/`DebugContext` methods, the `otelslog` side receives the context directly. That means trace/span correlation is handled by the OpenTelemetry logging pipeline without the SDK needing to manually inject `trace_id` fields into that branch. ## Two Common Setups ### 1. Stdout only If you do not configure an OpenTelemetry logger provider, logs only go to the normal SDK logger output. This does not restrict you from log correlation, however. For trace correlation in tools such as Grafana Tempo and Loki, you can: 1. Emit JSON logs to stdout/stderr. 2. Scrape those logs with an agent such as the OpenTelemetry Collector filelog receiver. 3. Forward them to Loki. 4. Query by the `trace_id` field in the logs. Remember, `trace_id` is only injected into the log if a contextual method was called with a context that contains an active span. ### 2. OpenTelemetry log exporter enabled If `otel.yaml` enables an OpenTelemetry log pipeline with real log processors/exporters, the SDK configures a `MultiLogger`. In that setup: * console logging still works as before * logs are also exported through OpenTelemetry * context-aware log calls carry trace context into the OpenTelemetry branch as well This is the path to use when you want the SDK to write logs directly into an OpenTelemetry logging backend, which eliminates the need to set up scraping infrastructure. ## Future Direction Today the SDK uses a `MultiLogger` because the default logger is `zerolog`, while OpenTelemetry currently offers a bridge for `slog` rather than `zerolog`. If a first-class `zerolog` bridge becomes available and suitable, that would likely be a simpler export path than maintaining a separate fanout logger. Relevant discussion: * [https://github.com/rs/zerolog/pull/682](https://github.com/rs/zerolog/pull/682) * [https://github.com/open-telemetry/opentelemetry-go-c
프로젝트로 돌아가기