Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions content/docs/architecture/meta.ru.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"title": "Архитектура",
"pages": [
"mvs-dependency-resolution"
]
}
14 changes: 7 additions & 7 deletions content/docs/architecture/mvs-dependency-resolution.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ A commit is not considered “newer” than a minimum version based on its date
~~~text
user
├── common v1.2.0
└── weather v2.1.0
└── weather/v2 v2.1.0
└── common v1.3.0
~~~

The <code>user</code> graph selects <code>common v1.3.0</code> and <code>weather v2.1.0</code>. Numerically, <code>v1.3.0</code> satisfies both common minimums; dependency resolution does not prove schema compatibility. Run <code>easyp breaking</code> separately for that check.
The <code>user</code> graph selects <code>common v1.3.0</code> and <code>weather/v2 v2.1.0</code>. Numerically, <code>v1.3.0</code> satisfies both common minimums; dependency resolution does not prove schema compatibility. Run <code>easyp breaking</code> separately for that check.

If user pins a SHA, the selected <code>common v1.3.0</code> tag must point to that exact commit. A <code>v1.2.0</code> tag at that SHA is insufficient when the maximum requirement is <code>v1.3.0</code>. If user's common requirement has no version, weather's semantic minimum determines the selection.

## Module and descriptor boundaries

Each module has its own <code>protobuf.mod</code> and <code>protobuf.lock</code>. For example, <code>proto/user</code> can select <code>common v1.3.0</code> while <code>proto/order</code> selects <code>common v2.0.0</code> in an independent graph.
Each module has its own <code>protobuf.mod</code> and <code>protobuf.lock</code>. For example, <code>proto/user</code> can select <code>common v1.3.0</code> while <code>proto/order</code> selects <code>common/v2 v2.0.0</code> in an independent graph.

Independent graphs do not guarantee that their combined generation output is compatible:

Expand All @@ -52,14 +52,14 @@ module github.com/acme/user
roots proto
require (
github.com/acme/common v1.2.0
github.com/acme/weather v2.1.0
github.com/acme/weather/v2 v2.1.0
)
replace github.com/acme/weather => ../weather-fork
replace github.com/acme/weather/v2 => ../weather-fork
~~~

<code>roots</code> is relative to the manifest directory and defaults to <code>.</code>. The <code>get</code> and <code>mod</code> commands find the nearest ancestor manifest within the workspace. Transitive requirements are recorded with <code>// indirect</code>.

A relative <code>replace</code> target is resolved from its owning <code>protobuf.mod</code>; an absolute target is used directly. Generation and linting support local replacements. <code>get</code>, <code>mod tidy</code>, <code>mod update</code>, and <code>mod vendor</code> reject them: remove replacements before these commands create or use a reproducible Git lock. This is command validation, not a CI rule rejecting commits.
A relative <code>replace</code> target is resolved from its owning <code>protobuf.mod</code>; an absolute target is used directly. Outside <code>--frozen</code>, generation, linting, <code>get</code>, <code>mod tidy</code>, <code>mod update</code>, <code>mod download</code>, and <code>mod vendor</code> all operate on the local effective graph while keeping <code>protobuf.lock</code> byte-for-byte untouched (never creating a lock or writing local/fork-only transitives into it). Remove replacements and run <code>mod tidy</code> to produce a publishable lock. Only explicit <code>--frozen</code> rejects <code>replace</code> directives (including unused ones) before accessing paths or fetching dependencies.

For nested Git modules, require each identity declared by its manifest. Versionless requirements need no tags. Version <code>v1.2.3</code> of a module in <code>proto/user</code> uses tag <code>proto/user/v1.2.3</code>.

Expand All @@ -78,7 +78,7 @@ modules:

During <code>tidy</code>, <code>get</code>, and <code>update</code>, a fetched previously locked SemVer must match its recorded commit and hash. A mismatch raises <code>ErrLockedVersionChanged</code> before installing the new graph or writing the manifest or lock, including for transitive requirements and warm caches. A new version may be selected; unconstrained versionless requirements still refresh to HEAD, while explicit SHAs stay pinned.

<code>mod download</code> can retrieve the old commit after a tag moves if that commit remains available. The Go <code>dirhash.Hash1</code> digest covers Git-tracked regular files with repository-relative paths. Both newly downloaded and installed cached files are verified.
<code>mod download</code> can retrieve the old commit after a tag moves if that commit remains available. The Go <code>dirhash.Hash1</code> digest is selective: it covers the materialized logical snapshot of selected <code>.proto</code> files and canonical EasyP/Buf configuration metadata (with repository-relative paths), omitting unrelated application code, documentation, and build outputs. Both newly downloaded and installed cached files are verified.

## Git object reuse

Expand Down
14 changes: 7 additions & 7 deletions content/docs/architecture/mvs-dependency-resolution.ru.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ EasyP разрешает зависимости отдельно для кажд
~~~text
user
├── common v1.2.0
└── weather v2.1.0
└── weather/v2 v2.1.0
└── common v1.3.0
~~~

Граф <code>user</code> выбирает <code>common v1.3.0</code> и <code>weather v2.1.0</code>. Численно <code>v1.3.0</code> удовлетворяет обоим минимумам common; разрешение версий само по себе не доказывает совместимость схем. Для этого отдельно запускают <code>easyp breaking</code>.
Граф <code>user</code> выбирает <code>common v1.3.0</code> и <code>weather/v2 v2.1.0</code>. Численно <code>v1.3.0</code> удовлетворяет обоим минимумам common; разрешение версий само по себе не доказывает совместимость схем. Для этого отдельно запускают <code>easyp breaking</code>.

Если user закрепляет SHA, выбранный тег <code>common v1.3.0</code> должен указывать именно на него. Самого наличия тега <code>v1.2.0</code> на этом SHA недостаточно, если максимум требований — <code>v1.3.0</code>. Если требование user к common не содержит версии, минимум weather определяет выбор.

## Границы модулей и дескрипторов

Каждый модуль имеет свой <code>protobuf.mod</code> и <code>protobuf.lock</code>. Например, <code>proto/user</code> может выбрать <code>common v1.3.0</code>, а <code>proto/order</code> — <code>common v2.0.0</code> в независимых графах.
Каждый модуль имеет свой <code>protobuf.mod</code> и <code>protobuf.lock</code>. Например, <code>proto/user</code> может выбрать <code>common v1.3.0</code>, а <code>proto/order</code> — <code>common/v2 v2.0.0</code> в независимых графах.

При генерации независимость графов не гарантирует совместимость объединённого результата:

Expand All @@ -52,14 +52,14 @@ module github.com/acme/user
roots proto
require (
github.com/acme/common v1.2.0
github.com/acme/weather v2.1.0
github.com/acme/weather/v2 v2.1.0
)
replace github.com/acme/weather => ../weather-fork
replace github.com/acme/weather/v2 => ../weather-fork
~~~

<code>roots</code> считается от каталога манифеста и по умолчанию равен <code>.</code>. Команды <code>get</code> и <code>mod</code> находят ближайший манифест в предках в пределах workspace. Транзитивные требования записываются с <code>// indirect</code>.

Относительная цель <code>replace</code> считается от содержащего её <code>protobuf.mod</code>, абсолютная используется напрямую. Генерация и линтинг поддерживают локальные замены. <code>get</code>, <code>mod tidy</code>, <code>mod update</code> и <code>mod vendor</code> отклоняют их: уберите замены перед созданием или использованием воспроизводимого Git lock этими командами. Это проверка команд, а не запрет коммитов со стороны CI.
Относительная цель <code>replace</code> считается от содержащего её <code>protobuf.mod</code>, абсолютная используется напрямую. Без <code>--frozen</code> генерация, линтинг, <code>get</code>, <code>mod tidy</code>, <code>mod update</code>, <code>mod download</code> и <code>mod vendor</code> работают с локальным эффективным графом, оставляя <code>protobuf.lock</code> побайтно неизменным (отсутствующий lock не создаётся, а локальные и форковые транзитивные зависимости в него не попадают). Чтобы получить публикуемый lock, удалите замены и выполните <code>mod tidy</code>. Отклоняет директивы <code>replace</code> (включая неиспользуемые) только явный режим <code>--frozen</code>.

Для вложенных Git-модулей каждое требование использует имя из соответствующего манифеста. Требование без версии не нуждается в теге. Версия <code>v1.2.3</code> модуля в <code>proto/user</code> использует тег <code>proto/user/v1.2.3</code>.

Expand All @@ -78,7 +78,7 @@ modules:

При <code>tidy</code>, <code>get</code> и <code>update</code> повторно полученный ранее зафиксированный SemVer должен совпасть с записанными коммитом и хешем. Несовпадение вызывает <code>ErrLockedVersionChanged</code> до установки нового графа и записи манифеста или lock, в том числе для транзитивных требований и прогретого кеша. Новая версия может быть выбрана; неограниченные требования без версии по-прежнему обновляются до HEAD, явные SHA сохраняются.

<code>mod download</code> может получить старый коммит после переноса тега, если коммит остаётся доступным. Хеш Go <code>dirhash.Hash1</code> охватывает обычные файлы, отслеживаемые Git, с путями относительно репозитория. Проверка выполняется и для новых загрузок, и для установленных файлов кеша.
<code>mod download</code> может получить старый коммит после переноса тега, если коммит остаётся доступным. Хеш Go <code>dirhash.Hash1</code> является селективным: он охватывает материализованный логический снимок только выбранных <code>.proto</code>-файлов и канонических конфигов EasyP/Buf (с путями относительно репозитория), пропуская посторонний код приложения, документацию и артефакты сборки. Проверка выполняется и для новых загрузок, и для установленных файлов кеша.

## Повторное использование Git-объектов

Expand Down
7 changes: 7 additions & 0 deletions content/docs/blog/meta.ru.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"title": "Блог",
"pages": [
"finally-give-up-gin-echo",
"working-with-proto-errors-correctly"
]
}
60 changes: 34 additions & 26 deletions content/docs/blog/working-with-proto-errors-correctly.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,11 @@ The gRPC system itself has the ability to attach additional data to an error —

```go
import (
"google.golang.org/grpc/status"
"google.golang.org/grpc/codes"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"fmt"

"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

// ...
Expand All @@ -78,7 +80,7 @@ errInfo := &errdetails.ErrorInfo{

st, err := st.WithDetails(errInfo)
if err != nil {
return fmt.Sprintf("st.WithDetails: %w", err)
return fmt.Errorf("st.WithDetails: %w", err)
}

return st.Err()
Expand Down Expand Up @@ -108,24 +110,25 @@ Now that we have the custom error definition, we can use it to pass more specifi

```go
import (
"google.golang.org/grpc/status"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/types/known/anypb"
"myerrors"
"fmt"

"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"myerrors"
)

// ...

customErrorDetail := &myerrors.CustomErrorDetail{
Reason: "Value out of range",
Field: "age",
Help: "The age must be between 0 and 120",
Reason: "Value out of range",
Field: "age",
Help: "The age must be between 0 and 120",
}

st := status.New(codes.InvalidArgument, "invalid parameter")
st, err = st.WithDetails(customErrorDetail)
st, err := st.WithDetails(customErrorDetail)
if err != nil {
return fmt.Sprintf("Unexpected error attaching custom error detail: %w", err)
return fmt.Errorf("unexpected error attaching custom error detail: %w", err)
}

return st.Err()
Expand All @@ -141,19 +144,24 @@ When a client receives a response from a gRPC server, it can check for errors us

```go
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"log"
"context"
"log"

"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)

func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
conn, err := grpc.NewClient(
"localhost:50051",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()

client := NewYourServiceClient(conn)
response, err := client.YourMethod(context.Background(), &YourRequest{})
Expand Down Expand Up @@ -205,14 +213,14 @@ func handleError(err error) {
case *errdetails.BadRequest:
// Handle bad request details
for _, violation := range t.GetFieldViolations() {
log.Printf("The field %s was wrong: %s\\n", violation.GetField(), violation.GetDescription())
log.Printf("The field %s was wrong: %s\n", violation.GetField(), violation.GetDescription())
}
case *myerrors.CustomErrorDetail:
// Handle custom error details
log.Printf("Custom error detail: Reason: %s, Field: %s, Help: %s\\n", t.Reason, t.Field, t.Help)
log.Printf("Custom error detail: Reason: %s, Field: %s, Help: %s\n", t.Reason, t.Field, t.Help)
// Add handling for other error types as necessary
default:
log.Printf("Received an unknown error detail type: %v\\n", t)
log.Printf("Received an unknown error detail type: %v\n", t)
}
}
}
Expand Down
Loading
Loading