CodeSampleX

샘플

google.golang.org/protobuf v1.35.1: anypb.Any

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

sha256:64b6dbcd54d4cce2b4a120e5bc0fb28b58b1adeee62b5982650ad710b80d5455

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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/anypb.Any in pkg:golang/google.golang.org/protobuf@v1.35.1
패키지
심벌
  • google.golang.org/protobuf/types/known/anypb.Any
생성일
2026-08-27T10:30:11Z

컨트랙트

  1. anypb.New packs a proto.Message into an *anypb.Any with proper TypeUrl and marshaled binary value
  2. anypb.Any.MessageIs correctly identifies matching and non-matching message descriptor types
  3. anypb.Any.UnmarshalTo extracts payload into target message and rejects type mismatches with an error
  4. anypb.Any.UnmarshalNew dynamically instantiates and unmarshals the registered message type
  5. anypb.Any.MarshalFrom overwrites an existing Any message with a new proto.Message payload
  6. anypb.Any.MessageName returns the protoreflect.FullName of the enclosed message

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

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

소스

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/anypb.Any 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/anypb.Any

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:bffbd910417224365c369629322cecc59481ff334e7f8e9c06f9efabdfdec293","contract":["anypb.New packs a proto.Message into an *anypb.Any with proper TypeUrl and marshaled binary value","anypb.Any.MessageIs correctly identifies matching and non-matching message descriptor types","anypb.Any.UnmarshalTo extracts payload into target message and rejects type mismatches with an error","anypb.Any.UnmarshalNew dynamically instantiates and unmarshals the registered message type","anypb.Any.MarshalFrom overwrites an existing Any message with a new proto.Message payload","anypb.Any.MessageName returns the protoreflect.FullName of the enclosed message"],"goal":"verify google.golang.org/protobuf/types/known/anypb.Any 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/anypb.Any"]},"contractCommand":["go","run","./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/anypb.Any"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

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=
main.go
package main

import (
	"fmt"
	"time"

	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// Container demonstrates packing dynamic payloads into an anypb.Any field.
type Container struct {
	Name    string
	Payload *anypb.Any
}

// PackMessage wraps any proto.Message into a Container.
func PackMessage(name string, msg proto.Message) (*Container, error) {
	anyMsg, err := anypb.New(msg)
	if err != nil {
		return nil, fmt.Errorf("failed to pack into Any: %w", err)
	}
	return &Container{
		Name:    name,
		Payload: anyMsg,
	}, nil
}

// UnpackPayload extracts the inner proto.Message from Container into dst.
func (c *Container) UnpackPayload(dst proto.Message) error {
	if c.Payload == nil {
		return fmt.Errorf("payload is nil")
	}
	return c.Payload.UnmarshalTo(dst)
}

func main() {
	// 1. Pack a timestamppb.Timestamp into Any
	now := time.Date(2026, 8, 27, 10, 0, 0, 0, time.UTC)
	tsMsg := timestamppb.New(now)

	container, err := PackMessage("event_timestamp", tsMsg)
	if err != nil {
		fmt.Printf("Error packing timestamp: %v\n", err)
		return
	}

	fmt.Printf("Container name: %s, TypeUrl: %s\n", container.Name, container.Payload.GetTypeUrl())

	// 2. Check type with MessageIs
	if container.Payload.MessageIs(&timestamppb.Timestamp{}) {
		fmt.Println("Payload contains a Timestamp message.")
	}

	// 3. Unpack using UnmarshalTo
	var unpackedTs timestamppb.Timestamp
	if err := container.UnpackPayload(&unpackedTs); err != nil {
		fmt.Printf("Error unpacking timestamp: %v\n", err)
		return
	}
	fmt.Printf("Unpacked time: %v\n", unpackedTs.AsTime())

	// 4. Dynamic unpack using UnmarshalNew
	dynamicMsg, err := container.Payload.UnmarshalNew()
	if err != nil {
		fmt.Printf("Error dynamic unpacking: %v\n", err)
		return
	}
	fmt.Printf("Dynamic message type: %T, value: %v\n", dynamicMsg, dynamicMsg)

	// 5. Update payload using MarshalFrom
	durMsg := durationpb.New(5 * time.Minute)
	if err := container.Payload.MarshalFrom(durMsg); err != nil {
		fmt.Printf("Error marshaling duration into Any: %v\n", err)
		return
	}
	fmt.Printf("Updated Container TypeUrl: %s\n", container.Payload.GetTypeUrl())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/types/known/anypb.Any 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/anypb.Any"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"time"

	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	// Assertion 1: anypb.New packs a proto.Message into an *anypb.Any with proper TypeUrl and marshaled binary value
	{
		origTs := timestamppb.New(time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC))
		anyMsg, err := anypb.New(origTs)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed for Timestamp: %v\n", err)
			os.Exit(1)
		}
		if anyMsg == nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New returned nil\n")
			os.Exit(1)
		}
		expectedTypeURL := "type.googleapis.com/google.protobuf.Timestamp"
		if anyMsg.GetTypeUrl() != expectedTypeURL {
			fmt.Fprintf(os.Stderr, "FAIL: TypeUrl mismatch: got %q, want %q\n", anyMsg.GetTypeUrl(), expectedTypeURL)
			os.Exit(1)
		}
		if len(anyMsg.GetValue()) == 0 {
			fmt.Fprintf(os.Stderr, "FAIL: anyMsg.Value is empty\n")
			os.Exit(1)
		}
	}

	// Assertion 2: anypb.Any.MessageIs correctly identifies matching and non-matching message descriptor types
	{
		origDur := durationpb.New(10 * time.Minute)
		anyMsg, err := anypb.New(origDur)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed for Duration: %v\n", err)
			os.Exit(1)
		}

		if !anyMsg.MessageIs(&durationpb.Duration{}) {
			fmt.Fprintf(os.Stderr, "FAIL: MessageIs returned false for matching Duration\n")
			os.Exit(1)
		}
		if anyMsg.MessageIs(&timestamppb.Timestamp{}) {
			fmt.Fprintf(os.Stderr, "FAIL: MessageIs returned true for non-matching Timestamp\n")
			os.Exit(1)
		}
	}

	// Assertion 3: anypb.Any.UnmarshalTo extracts payload into target message and rejects type mismatches with an error
	{
		origTs := timestamppb.New(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
		anyMsg, err := anypb.New(origTs)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed: %v\n", err)
			os.Exit(1)
		}

		var unpackedTs timestamppb.Timestamp
		if err := anyMsg.UnmarshalTo(&unpackedTs); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalTo failed for matching type: %v\n", err)
			os.Exit(1)
		}
		if !proto.Equal(origTs, &unpackedTs) {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalTo result does not match original\n")
			os.Exit(1)
		}

		var wrongDst durationpb.Duration
		if err := anyMsg.UnmarshalTo(&wrongDst); err == nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalTo should return error for mismatched message type\n")
			os.Exit(1)
		}
	}

	// Assertion 4: anypb.Any.UnmarshalNew dynamically instantiates and unmarshals the registered message type
	{
		origDur := durationpb.New(42 * time.Second)
		anyMsg, err := anypb.New(origDur)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed: %v\n", err)
			os.Exit(1)
		}

		dynamicMsg, err := anyMsg.UnmarshalNew()
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalNew failed: %v\n", err)
			os.Exit(1)
		}
		durVal, ok := dynamicMsg.(*durationpb.Duration)
		if !ok {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalNew returned unexpected type %T\n", dynamicMsg)
			os.Exit(1)
		}
		if !proto.Equal(origDur, durVal) {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalNew content does not match original\n")
			os.Exit(1)
		}
	}

	// Assertion 5: anypb.Any.MarshalFrom overwrites an existing Any message with a new proto.Message payload
	{
		anyMsg := &anypb.Any{}
		ts := timestamppb.New(time.Date(2025, 5, 20, 15, 30, 0, 0, time.UTC))
		if err := anyMsg.MarshalFrom(ts); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalFrom failed: %v\n", err)
			os.Exit(1)
		}
		if !anyMsg.MessageIs(&timestamppb.Timestamp{}) {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalFrom did not set expected TypeUrl\n")
			os.Exit(1)
		}

		dur := durationpb.New(100 * time.Millisecond)
		if err := anyMsg.MarshalFrom(dur); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalFrom second write failed: %v\n", err)
			os.Exit(1)
		}
		if !anyMsg.MessageIs(&durationpb.Duration{}) {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalFrom did not overwrite TypeUrl\n")
			os.Exit(1)
		}
	}

	// Assertion 6: anypb.Any.MessageName returns the protoreflect.FullName of the enclosed message
	{
		ts := timestamppb.New(time.Now())
		anyMsg, err := anypb.New(ts)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed: %v\n", err)
			os.Exit(1)
		}
		msgName := anyMsg.MessageName()
		expectedName := protoreflect.FullName("google.protobuf.Timestamp")
		if msgName != expectedName {
			fmt.Fprintf(os.Stderr, "FAIL: MessageName mismatch: got %q, want %q\n", msgName, expectedName)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: google.golang.org/protobuf/types/known/anypb.Any contract passed")
}

오리진 시더

익명