CodeSampleX

샘플

google.golang.org/protobuf v1.35.1: durationpb.New

검증된 샘플 — golang google.golang.org/protobuf v1.35.1: durationpb.New. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:7f79ef0e71f5811e50d337dc6e0f605ef3b855b43f73481ad07c06938931c8b0

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

케이스

HOW
목표
verify google.golang.org/protobuf/types/known/durationpb.New in pkg:golang/google.golang.org/protobuf@v1.35.1
패키지
심벌
  • google.golang.org/protobuf/types/known/durationpb.New
생성일
2026-08-27T10:39:50Z

컨트랙트

  1. durationpb.New converts time.Duration into *durationpb.Duration with corresponding Seconds and Nanos fields, where negative durations have both negative Seconds and negative Nanos.
  2. durationpb.Duration.AsDuration converts the protobuf message back to time.Duration, and calling AsDuration on a nil receiver safely returns 0.
  3. durationpb.Duration.CheckValid and IsValid validate duration bounds within +/-10,000 years and reject sign discrepancies between Seconds and Nanos or out-of-range nanoseconds.
  4. durationpb.Duration supports protobuf wire serialization and protojson serialization formatting as a string with a trailing 's' suffix.

파일

  • NOTES.md
  • PROMPT.md
  • csx.json
  • duration_test.go
  • go.mod
  • go.sum
  • spec.json

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Protocol Buffers Duration Well-Known Type Behavior

A known-solution search for `google.golang.org/protobuf/types/known/durationpb.New` in package `pkg:golang/google.golang.org/protobuf@v1.35.1` returned no safe match. This sample verifies the construction, conversion, validation, and serialization semantics of `google.protobuf.Duration` using `durationpb.New`.

## Observed Behavior

1. **Conversion with `durationpb.New`**:
   - `durationpb.New(d)` converts a standard Go `time.Duration` into a protobuf `*durationpb.Duration` message consisting of `Seconds` (`int64`) and `Nanos` (`int32`).
   - For positive durations, both `Seconds` and `Nanos` are non-negative.
   - For negative durations, protobuf specification dictates that both `Seconds` and `Nanos` carry negative signs (e.g., `-1.75s` maps to `Seconds: -1, Nanos: -750000000`).
   - Sub-second negative durations (e.g., `-250ms`) map to `Seconds: 0, Nanos: -250000000`.

2. **Reconstitution and Nil Safety (`AsDuration`)**:
   - `pb.AsDuration()` accurately converts the protobuf `*durationpb.Duration` back into a Go `time.Duration`.
   - Calling `(*durationpb.Duration)(nil).AsDuration()` is safe and returns `time.Duration(0)` without panicking.

3. **Validation Semantics (`CheckValid` and `IsValid`)**:
   - Durations are valid only if `Seconds` is within `[-315576000000, +315576000000]` (representing approx. ±10,000 years), `Nanos` is within `[-999999999, +999999999]`, and `Seconds` and `Nanos` have consistent signs (or zero).
   - Sign mismatch (such as `Seconds: 1, Nanos: -1` or `Seconds: -1, Nanos: 1`) is invalid and causes `CheckValid()` to return an error.
   - Nil receiver reports `IsValid() == false` and `CheckValid()` returns a non-nil error.

4. **Wire and JSON Serialization**:
   - `proto.Marshal` and `proto.Unmarshal` preserve binary representations.
   - `protojson.Marshal` serializes the well-known duration type to canonical JSON string format with a trailing `"s"` (e.g., `"1.500s"`, `"-0.25s"`).
   - `protojson.Unmarshal` parses canonical duration strings into `*durationpb.Duration`.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify google.golang.org/protobuf/types/known/durationpb.New in pkg:golang/google.golang.org/protobuf@v1.35.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.35.1
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/types/known/durationpb.New

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:cd81f6ebf160e6440a0b14eb3c02a92678b5a24478d2c40368c11c50aaa246f1","contract":["durationpb.New converts time.Duration into *durationpb.Duration with corresponding Seconds and Nanos fields, where negative durations have both negative Seconds and negative Nanos.","durationpb.Duration.AsDuration converts the protobuf message back to time.Duration, and calling AsDuration on a nil receiver safely returns 0.","durationpb.Duration.CheckValid and IsValid validate duration bounds within +/-10,000 years and reject sign discrepancies between Seconds and Nanos or out-of-range nanoseconds.","durationpb.Duration supports protobuf wire serialization and protojson serialization formatting as a string with a trailing 's' suffix."],"goal":"verify google.golang.org/protobuf/types/known/durationpb.New in pkg:golang/google.golang.org/protobuf@v1.35.1","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.35.1"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/types/known/durationpb.New"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.35.1"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.35.1","symbols":["google.golang.org/protobuf/types/known/durationpb.New"],"verifierAdapter":"golang@1"}
duration_test.go
package durationpbtest

import (
	"testing"
	"time"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/durationpb"
)

func TestDurationpbNewAndAsDuration(t *testing.T) {
	tests := []struct {
		name        string
		input       time.Duration
		wantSec     int64
		wantNanos   int32
	}{
		{
			name:      "zero duration",
			input:     0,
			wantSec:   0,
			wantNanos: 0,
		},
		{
			name:      "positive whole seconds",
			input:     5 * time.Second,
			wantSec:   5,
			wantNanos: 0,
		},
		{
			name:      "positive compound duration",
			input:     2*time.Second + 500*time.Millisecond + 123*time.Nanosecond,
			wantSec:   2,
			wantNanos: 500000123,
		},
		{
			name:      "negative whole seconds",
			input:     -3 * time.Second,
			wantSec:   -3,
			wantNanos: 0,
		},
		{
			name:      "negative sub-second duration",
			input:     -250 * time.Millisecond,
			wantSec:   0,
			wantNanos: -250000000,
		},
		{
			name:      "negative compound duration",
			input:     -1*time.Second - 750*time.Millisecond,
			wantSec:   -1,
			wantNanos: -750000000,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			pb := durationpb.New(tc.input)
			if pb == nil {
				t.Fatalf("durationpb.New(%v) returned nil", tc.input)
			}
			if got := pb.GetSeconds(); got != tc.wantSec {
				t.Errorf("GetSeconds() = %d, want %d", got, tc.wantSec)
			}
			if got := pb.GetNanos(); got != tc.wantNanos {
				t.Errorf("GetNanos() = %d, want %d", got, tc.wantNanos)
			}

			// AsDuration should round-trip back to original time.Duration
			gotDur := pb.AsDuration()
			if gotDur != tc.input {
				t.Errorf("AsDuration() = %v, want %v", gotDur, tc.input)
			}
		})
	}

	// Verify nil receiver returns 0 duration safely
	var nilPb *durationpb.Duration
	if got := nilPb.AsDuration(); got != 0 {
		t.Errorf("(*durationpb.Duration)(nil).AsDuration() = %v, want 0", got)
	}
}

func TestDurationpbValidation(t *testing.T) {
	// Valid cases
	validCases := []*durationpb.Duration{
		durationpb.New(0),
		durationpb.New(10 * time.Minute),
		durationpb.New(-10 * time.Minute),
		{Seconds: 315576000000, Nanos: 999999999},
		{Seconds: -315576000000, Nanos: -999999999},
	}
	for _, d := range validCases {
		if !d.IsValid() {
			t.Errorf("expected %v to be valid", d)
		}
		if err := d.CheckValid(); err != nil {
			t.Errorf("CheckValid() for %v returned unexpected error: %v", d, err)
		}
	}

	// Nil receiver validation
	var nilPb *durationpb.Duration
	if nilPb.IsValid() {
		t.Errorf("nil duration must report IsValid() == false")
	}
	if err := nilPb.CheckValid(); err == nil {
		t.Errorf("nil duration must return non-nil error from CheckValid()")
	}

	// Invalid cases: sign mismatch, out-of-range nanos, out-of-range seconds
	invalidCases := []struct {
		name string
		dur  *durationpb.Duration
	}{
		{
			name: "positive seconds with negative nanos",
			dur:  &durationpb.Duration{Seconds: 1, Nanos: -1},
		},
		{
			name: "negative seconds with positive nanos",
			dur:  &durationpb.Duration{Seconds: -1, Nanos: 1},
		},
		{
			name: "nanos overflow positive (>= 1e9)",
			dur:  &durationpb.Duration{Seconds: 0, Nanos: 1000000000},
		},
		{
			name: "nanos underflow negative (<= -1e9)",
			dur:  &durationpb.Duration{Seconds: 0, Nanos: -1000000000},
		},
		{
			name: "seconds exceed upper bound (+315576000000)",
			dur:  &durationpb.Duration{Seconds: 315576000001, Nanos: 0},
		},
		{
			name: "seconds exceed lower bound (-315576000000)",
			dur:  &durationpb.Duration{Seconds: -315576000001, Nanos: 0},
		},
	}

	for _, tc := range invalidCases {
		t.Run(tc.name, func(t *testing.T) {
			if tc.dur.IsValid() {
				t.Errorf("expected IsValid() == false for %s (%v)", tc.name, tc.dur)
			}
			if err := tc.dur.CheckValid(); err == nil {
				t.Errorf("expected CheckValid() to fail for %s (%v)", tc.name, tc.dur)
			}
		})
	}
}

func TestDurationpbSerialization(t *testing.T) {
	orig := durationpb.New(1500 * time.Millisecond)

	// Binary proto serialization round-trip
	data, err := proto.Marshal(orig)
	if err != nil {
		t.Fatalf("proto.Marshal failed: %v", err)
	}
	var unmarshaled durationpb.Duration
	if err := proto.Unmarshal(data, &unmarshaled); err != nil {
		t.Fatalf("proto.Unmarshal failed: %v", err)
	}
	if !proto.Equal(orig, &unmarshaled) {
		t.Errorf("unmarshaled message %v != original %v", &unmarshaled, orig)
	}

	// JSON format serialization (well-known duration formats with "s" suffix)
	jsonBytes, err := protojson.Marshal(orig)
	if err != nil {
		t.Fatalf("protojson.Marshal failed: %v", err)
	}
	wantJSON := `"1.500s"`
	if string(jsonBytes) != wantJSON {
		t.Errorf("protojson.Marshal() = %s, want %s", string(jsonBytes), wantJSON)
	}

	// JSON format parsing
	var fromJSON durationpb.Duration
	if err := protojson.Unmarshal([]byte(`"-2.5s"`), &fromJSON); err != nil {
		t.Fatalf("protojson.Unmarshal failed: %v", err)
	}
	if gotSec, gotNanos := fromJSON.GetSeconds(), fromJSON.GetNanos(); gotSec != -2 || gotNanos != -500000000 {
		t.Errorf("fromJSON = seconds:%d nanos:%d, want seconds:-2 nanos:-500000000", gotSec, gotNanos)
	}
}
go.mod
module example.com/durationpb-verify

go 1.22.0

require google.golang.org/protobuf v1.35.1
go.sum
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/types/known/durationpb.New in pkg:golang/google.golang.org/protobuf@v1.35.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.35.1"
  ],
  "symbols": [
    "google.golang.org/protobuf/types/known/durationpb.New"
  ]
}

오리진 시더

익명