项目文件夹

文件
T
Asim Aslam 76bfeae456 Claude/update docs roadmap f zd2 j (#2880)
* docs: update all four documentation guides and mark Q2 complete

- ai-native-services: add WithMCP one-liner, standalone gateway,
  WebSocket client example, and OpenTelemetry observability section
- mcp-security: add OTel distributed tracing, WebSocket authentication
  (connection-level and per-message), DeniedReason audit field
- tool-descriptions: add manual overrides with WithEndpointDocs and
  export formats section
- agent-patterns: add LangChain/LlamaIndex SDK pattern and standalone
  gateway production pattern with Docker example
- Update roadmap: mark Q2 documentation as complete, Q2 at 100%
- Update status: reflect all recent completions, shift priorities

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: add agent demo example and blog post

Add examples/agent-demo with a multi-service project management app
(projects, tasks, team) that demonstrates AI agents interacting with
Go Micro services through MCP. Includes seed data and example prompts.

Add blog post 4 "Agents Meet Microservices: A Hands-On Demo" walking
through the example code and showing cross-service agent workflows.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: enable multiple services in a single binary

Remove global state mutations from service and cmd option functions so
that configuring one service no longer overwrites another's settings.

Key changes:
- service/options.go: remove all DefaultXxx global writes from option
  functions; newOptions() now creates fresh Server, Client, Store, and
  Cache per service while sharing Registry, Broker, and Transport
- cmd/cmd.go: newCmd() uses local copies instead of pointers to package
  globals; Before() no longer mutates DefaultXxx vars
- cmd/options.go: remove global mutations from all option functions
- service/service.go: export ServiceImpl type for cross-package use
- service/group.go: new Group type for multi-service lifecycle
- micro.go: add Start/Stop to Service interface, expose Group and
  NewGroup convenience function
- examples/multi-service: working example with two services

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* docs: highlight multi-service binary support

Add multi-service section to README with code example, update features
list, add to examples index, and note in status summary.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: unify service API and clean up developer experience

- Unified service creation: micro.New("name", opts...) as canonical API
- Clean handler registration: service.Handle(handler, opts...) accepts
  server.HandlerOption args directly, no need to reach through Server()
- Unexported serviceImpl: users interact through Service interface only
- Service groups use Service interface (not concrete type)
- Fixed Stop() to properly propagate BeforeStop/AfterStop errors
- Fixed store init: error-level log instead of fatal on init failure
- Updated all examples to use consistent patterns
- Updated README, getting-started, MCP docs, and guides
- Added blog post about the DX cleanup

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* fix: add blog post 5 to blog index

Blog post 5 (Developer Experience Cleanup) existed as a file but was
missing from the blog index page.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: make micro new generate MCP-enabled services by default

- main.go template includes mcp.WithMCP(":3001") by default
- Handler template has agent-friendly doc comments with @example tags
- Proto template has descriptive field comments
- README includes MCP usage, Claude Code config, and tool description tips
- Makefile adds mcp-tools, mcp-test, mcp-serve targets
- go.mod updated to Go 1.22
- Added --no-mcp flag to opt out of MCP integration
- Post-create output shows MCP endpoint URLs

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* docs: add MCP migration guide and troubleshooting guide

- Migration guide: 3 approaches to add MCP to existing services
  (WithMCP one-liner, standalone gateway, CLI)
- Troubleshooting guide: common issues with agents, WebSocket,
  Claude Code, auth, rate limiting, and performance

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: rename model/ package to ai/ for AI model providers

The model/ package name conflicted with the conventional use of "model"
for data models. Renamed to ai/ which better describes the package's
purpose (AI provider abstraction for Anthropic, OpenAI, etc.) and frees
up model/ for future data model layer use.

- Rename model/ → ai/ with package name change
- Update all Go imports from go-micro.dev/v5/model to go-micro.dev/v5/ai
- Update cmd/micro/server/server.go references (model.X → ai.X)
- Update all documentation and roadmap references
- All tests pass, CLI builds successfully

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: add model package for typed data access with CRUD and queries

New model/ package provides a typed data model layer using Go generics.
Supports structured CRUD operations, WHERE filters, ordering, pagination,
and automatic schema creation from struct tags.

Three backends:
- memory: in-memory for development and testing
- sqlite: embedded SQL for dev and single-node production
- postgres: full PostgreSQL for production deployments

Key features:
- Generic Model[T] with Create/Read/Update/Delete/List/Count
- Query builder: Where(), WhereOp(), OrderAsc/Desc(), Limit(), Offset()
- Struct tags: model:"key" for primary key, model:"index" for indexes
- Auto table creation from struct schema
- 19 tests passing across memory and sqlite backends

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: add model code generation to protoc-gen-micro

Extend the micro plugin to generate model structs from proto messages
annotated with // @model. Generated alongside client/server code in
the same .pb.micro.go file.

For a proto message like:
  // @model
  message User { string id = 1; string name = 2; }

Generates:
- UserModel struct with model:"key" and json tags
- NewUserModel(db) factory returning *model.Model[UserModel]
- UserModelFromProto(*User) *UserModel converter
- (*UserModel).ToProto() *User converter

Supports @model(table=custom_table, key=custom_field) options.
Adds GetComments() to generator for plugin comment inspection.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: add Model() to Service interface for Client/Server/Model trifecta

Every service now exposes Client(), Server(), and Model() — call services,
handle requests, and save/query data from the same interface. Includes
README docs, blog post, and a full model guide on the docs site.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 13:13:34 +00:00

252 行
6.9 KiB
Go

// Package model provides a typed data model layer with CRUD operations and query support.
// It uses Go generics for type-safe access and supports multiple backends (memory, SQLite, Postgres).
package model
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
)
var (
// ErrNotFound is returned when a record doesn't exist.
ErrNotFound = errors.New("not found")
// ErrDuplicateKey is returned when a record with the same key already exists.
ErrDuplicateKey = errors.New("duplicate key")
)
// Database is the backend interface that model implementations must satisfy.
// Each backend (memory, sqlite, postgres) implements this interface.
type Database interface {
// Init initializes the database connection.
Init(...Option) error
// NewTable ensures the table exists for the given schema.
NewTable(schema *Schema) error
// Create inserts a new record. Returns ErrDuplicateKey if key exists.
Create(ctx context.Context, schema *Schema, key string, fields map[string]any) error
// Read returns a single record by key. Returns ErrNotFound if missing.
Read(ctx context.Context, schema *Schema, key string) (map[string]any, error)
// Update modifies an existing record by key. Returns ErrNotFound if missing.
Update(ctx context.Context, schema *Schema, key string, fields map[string]any) error
// Delete removes a record by key. Returns ErrNotFound if missing.
Delete(ctx context.Context, schema *Schema, key string) error
// List returns all records matching the query options.
List(ctx context.Context, schema *Schema, opts ...QueryOption) ([]map[string]any, error)
// Count returns the number of records matching the query options.
Count(ctx context.Context, schema *Schema, opts ...QueryOption) (int64, error)
// Close closes the database connection.
Close() error
// String returns the implementation name.
String() string
}
// Schema describes a model's storage layout, derived from struct tags.
type Schema struct {
// Table name in the database.
Table string
// Key is the name of the primary key field.
Key string
// Fields maps Go field names to their column metadata.
Fields []Field
}
// Field describes a single field in the schema.
type Field struct {
// Name is the Go struct field name.
Name string
// Column is the database column name (from json tag or lowercased name).
Column string
// Type is the Go reflect type.
Type reflect.Type
// IsKey indicates this is the primary key field.
IsKey bool
// Index indicates this field should be indexed.
Index bool
}
// Model provides typed CRUD operations for a specific Go struct type.
type Model[T any] struct {
db Database
schema *Schema
}
// New creates a new Model for the given type T, backed by the provided database.
// T must be a struct with at least one field tagged `model:"key"`.
func New[T any](db Database, opts ...ModelOption) *Model[T] {
var t T
schema := buildSchema(reflect.TypeOf(t))
// Apply model options
for _, o := range opts {
o(schema)
}
// Ensure table exists
if err := db.NewTable(schema); err != nil {
panic(fmt.Sprintf("model: failed to create table %q: %v", schema.Table, err))
}
return &Model[T]{
db: db,
schema: schema,
}
}
// Create inserts a new record.
func (m *Model[T]) Create(ctx context.Context, v *T) error {
fields := structToMap(m.schema, v)
key, ok := fields[m.schema.Key]
if !ok {
return fmt.Errorf("model: key field %q not set", m.schema.Key)
}
return m.db.Create(ctx, m.schema, fmt.Sprint(key), fields)
}
// Read retrieves a record by its primary key.
func (m *Model[T]) Read(ctx context.Context, key string) (*T, error) {
fields, err := m.db.Read(ctx, m.schema, key)
if err != nil {
return nil, err
}
v := mapToStruct[T](m.schema, fields)
return v, nil
}
// Update modifies an existing record.
func (m *Model[T]) Update(ctx context.Context, v *T) error {
fields := structToMap(m.schema, v)
key, ok := fields[m.schema.Key]
if !ok {
return fmt.Errorf("model: key field %q not set", m.schema.Key)
}
return m.db.Update(ctx, m.schema, fmt.Sprint(key), fields)
}
// Delete removes a record by its primary key.
func (m *Model[T]) Delete(ctx context.Context, key string) error {
return m.db.Delete(ctx, m.schema, key)
}
// List returns records matching the query options.
func (m *Model[T]) List(ctx context.Context, opts ...QueryOption) ([]*T, error) {
rows, err := m.db.List(ctx, m.schema, opts...)
if err != nil {
return nil, err
}
results := make([]*T, len(rows))
for i, row := range rows {
results[i] = mapToStruct[T](m.schema, row)
}
return results, nil
}
// Count returns the number of records matching the query options.
func (m *Model[T]) Count(ctx context.Context, opts ...QueryOption) (int64, error) {
return m.db.Count(ctx, m.schema, opts...)
}
// Schema returns the model's schema (useful for debugging/introspection).
func (m *Model[T]) Schema() *Schema {
return m.schema
}
// buildSchema extracts the Schema from a struct type using reflection.
func buildSchema(t reflect.Type) *Schema {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
schema := &Schema{
Table: strings.ToLower(t.Name()) + "s",
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() {
continue
}
field := Field{
Name: f.Name,
Type: f.Type,
}
// Column name: use json tag if present, else lowercase field name
if tag := f.Tag.Get("json"); tag != "" {
parts := strings.Split(tag, ",")
if parts[0] != "" && parts[0] != "-" {
field.Column = parts[0]
}
}
if field.Column == "" {
field.Column = strings.ToLower(f.Name)
}
// Check model tag
if tag := f.Tag.Get("model"); tag != "" {
for _, opt := range strings.Split(tag, ",") {
switch opt {
case "key":
field.IsKey = true
schema.Key = field.Column
case "index":
field.Index = true
}
}
}
schema.Fields = append(schema.Fields, field)
}
if schema.Key == "" {
// Default to "id" if no key tag found
for i := range schema.Fields {
if schema.Fields[i].Column == "id" {
schema.Fields[i].IsKey = true
schema.Key = "id"
break
}
}
}
return schema
}
// structToMap converts a struct to a map of column name → value.
func structToMap[T any](schema *Schema, v *T) map[string]any {
rv := reflect.ValueOf(v).Elem()
fields := make(map[string]any, len(schema.Fields))
for _, f := range schema.Fields {
fv := rv.FieldByName(f.Name)
if fv.IsValid() {
fields[f.Column] = fv.Interface()
}
}
return fields
}
// mapToStruct converts a map of column name → value back to a struct.
func mapToStruct[T any](schema *Schema, fields map[string]any) *T {
v := new(T)
rv := reflect.ValueOf(v).Elem()
for _, f := range schema.Fields {
val, ok := fields[f.Column]
if !ok {
continue
}
fv := rv.FieldByName(f.Name)
if !fv.IsValid() || !fv.CanSet() {
continue
}
rval := reflect.ValueOf(val)
if rval.Type().AssignableTo(fv.Type()) {
fv.Set(rval)
} else if rval.Type().ConvertibleTo(fv.Type()) {
fv.Set(rval.Convert(fv.Type()))
}
}
return v
}