Publisher-managed "deleted" support (#893)

(Updated auto-generated PR description from @tadasant / Claude on Feb
22, 2026)

## Motivation and Context

Fixes #637

Server lifecycle management (deprecation and yanking) is a standard
requirement for package registries. Use cases like rebranding, security
vulnerabilities, and end-of-life servers demand the ability to mark
servers as deprecated or deleted, with optional messaging to guide
consumers toward alternatives.

## Changes

### New API endpoints

- **`PATCH /v0/servers/{serverName}/versions/{version}/status`** —
Update the lifecycle status of a single server version
- **`PATCH /v0/servers/{serverName}/status`** — Update the lifecycle
status of all versions of a server in a single transaction

Both endpoints accept:
```json
{
  "status": "active|deprecated|deleted",
  "statusMessage": "Optional message (max 500 chars) explaining the change"
}
```

### New CLI command

- **`mcp-publisher status <serverName> [version]`** — Update server
lifecycle status from the command line
  - `--status` (required): `active`, `deprecated`, or `deleted`
  - `--message`: Optional status message
- `--all-versions`: Apply to all versions of the server (replaces the
`<version>` argument)

### API response changes

`RegistryExtensions` now includes two new fields:
- `statusChangedAt` — Timestamp of the last status change
- `statusMessage` — Optional free-form message (e.g., deprecation
reason, migration guidance)

### List endpoint changes

- New `include_deleted` query parameter on `GET /v0/servers` — defaults
to `false`, hiding deleted servers from listings
- When `updated_since` is provided, `include_deleted` is automatically
set to `true` for incremental sync

### Database

- Migration `013_add_status_fields.sql`: Adds `status_changed_at` (NOT
NULL, initialized from `published_at`) and `status_message` columns to
the `servers` table

### Design decisions (from review discussion)

- **Dedicated status endpoints** rather than overloading the existing
edit endpoint
- **Bidirectional status transitions** — all transitions between
`active`, `deprecated`, and `deleted` are allowed
- **`statusMessage` as free-form text** — no structured `nextName` or
`alternativeUrl` fields (per maintainer feedback, to avoid complexity
around chaining, trust transfer, etc.)
- **Publish permission** grants status change access (not limited to
admin/edit)
- **Status message auto-cleared** when transitioning back to `active`
Good, now I have the full picture. Here's the addendum:

### Consumer-facing API changes

The new status fields live inside
`_meta["io.modelcontextprotocol.registry/official"]` on every
`ServerResponse`. This is the existing `RegistryExtensions` object — two
new fields are added alongside the existing ones:

**Before:**
```json
{
  "server": { "name": "com.example/my-server", "...": "..." },
  "_meta": {
    "io.modelcontextprotocol.registry/official": {
      "status": "active",
      "publishedAt": "2025-06-01T00:00:00Z",
      "updatedAt": "2025-06-15T00:00:00Z",
      "isLatest": true
    }
  }
}
```

**After:**
```json
{
  "server": { "name": "com.example/my-server", "...": "..." },
  "_meta": {
    "io.modelcontextprotocol.registry/official": {
      "status": "deprecated",
      "statusChangedAt": "2026-02-01T12:00:00Z",
      "statusMessage": "Deprecated in favor of com.example/my-server-v2",
      "publishedAt": "2025-06-01T00:00:00Z",
      "updatedAt": "2026-02-01T12:00:00Z",
      "isLatest": true
    }
  }
}
```

| New field | Type | Present when |
|-----------|------|-------------|
| `statusChangedAt` | `string` (RFC3339) | Always — initialized to
`publishedAt` for existing records |
| `statusMessage` | `string` (max 500 chars) | Only when set —
`null`/omitted for active servers (auto-cleared on transition to active)
|

These fields appear on **every endpoint that returns a
`ServerResponse`**: `GET /v0/servers`, `GET /v0/servers/{name}`, `GET
/v0/servers/{name}/versions/{version}`, and the new PATCH status
endpoints.

### List endpoint filtering

`GET /v0/servers` gains an `include_deleted` query parameter:

| Scenario | Behavior |
|----------|----------|
| No `include_deleted` param | Deleted servers hidden (default `false`)
|
| `include_deleted=true` | Deleted servers included in results |
| `updated_since` provided | `include_deleted` forced to `true` for
incremental sync |

## How Has This Been Tested?

- Unit tests for status handler (`status_test.go`) covering status
transitions, permission checks, validation errors, and the all-versions
endpoint
- Unit tests for the CLI command (`status_test.go`)
- Integration with existing server/edit handler tests
- Database layer tests for the new status update and query methods
- Tested locally with `make dev-compose`

## Types of changes

- [x] New feature (non-breaking change which adds functionality)

## Checklist

- [x] I have read the [MCP
Documentation](https://modelcontextprotocol.io)
- [x] My code follows the repository's style guidelines
- [x] New and existing tests pass locally
- [x] I have added appropriate error handling
- [x] I have added or updated documentation as needed

## Open items from review

- [ ] `include_deleted` silent override: When `updated_since` is
provided and `include_deleted=false` is explicitly passed, should return
a 400 error rather than silently overriding
([thread](https://github.com/modelcontextprotocol/registry/pull/893#discussion_r2100879360))
— agreed upon but may not yet be implemented
This commit is contained in:
Preeti Dewani 2026-02-27 22:30:07 +05:30 • committed by GitHub
commit bb84ea69e8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 4153 additions and 474 deletions

View file

@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
"github.com/modelcontextprotocol/registry/pkg/model"
)
// Common database errors
@ -21,12 +22,13 @@ var (
// ServerFilter defines filtering options for server queries
type ServerFilter struct {
Name *string // for finding versions of same server
RemoteURL *string // for duplicate URL detection
UpdatedSince *time.Time // for incremental sync filtering
SubstringName *string // for substring search on name
Version *string // for exact version matching
IsLatest *bool // for filtering latest versions only
Name *string // for finding versions of same server
RemoteURL *string // for duplicate URL detection
UpdatedSince *time.Time // for incremental sync filtering
SubstringName *string // for substring search on name
Version *string // for exact version matching
IsLatest *bool // for filtering latest versions only
IncludeDeleted *bool // for including deleted packages in results (default: exclude)
}
// Database defines the interface for database operations
@ -36,15 +38,17 @@ type Database interface {
// UpdateServer updates an existing server record
UpdateServer(ctx context.Context, tx pgx.Tx, serverName, version string, serverJSON *apiv0.ServerJSON) (*apiv0.ServerResponse, error)
// SetServerStatus updates the status of a specific server version
SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status string) (*apiv0.ServerResponse, error)
SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status model.Status, statusMessage *string) (*apiv0.ServerResponse, error)
// SetAllVersionsStatus updates the status of all versions of a server in a single query
SetAllVersionsStatus(ctx context.Context, tx pgx.Tx, serverName string, status model.Status, statusMessage *string) ([]*apiv0.ServerResponse, error)
// ListServers retrieve server entries with optional filtering
ListServers(ctx context.Context, tx pgx.Tx, filter *ServerFilter, cursor string, limit int) ([]*apiv0.ServerResponse, string, error)
// GetServerByName retrieve a single server by its name
GetServerByName(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error)
GetServerByName(ctx context.Context, tx pgx.Tx, serverName string, includeDeleted bool) (*apiv0.ServerResponse, error)
// GetServerByNameAndVersion retrieve specific version of a server by server name and version
GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string) (*apiv0.ServerResponse, error)
GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string, includeDeleted bool) (*apiv0.ServerResponse, error)
// GetAllVersionsByServerName retrieve all versions of a server by server name
GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string) ([]*apiv0.ServerResponse, error)
GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string, includeDeleted bool) ([]*apiv0.ServerResponse, error)
// GetCurrentLatestVersion retrieve the current latest version of a server by server name
GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error)
// CountServerVersions count the number of versions for a server

View file

@ -0,0 +1,24 @@
-- Add status management fields for deprecation features
-- Status values: active, deprecated, deleted
BEGIN;
-- Add new columns for status management
ALTER TABLE servers ADD COLUMN status_changed_at TIMESTAMP WITH TIME ZONE;
ALTER TABLE servers ADD COLUMN status_message TEXT;
-- Constraint: status_message must not exceed 500 characters
ALTER TABLE servers ADD CONSTRAINT check_status_message_length
CHECK (length(status_message) <= 500);
-- Initialize status_changed_at with published_at for existing records
UPDATE servers SET status_changed_at = published_at WHERE status_changed_at IS NULL;
-- Make status_changed_at NOT NULL now that all records have values
ALTER TABLE servers ALTER COLUMN status_changed_at SET NOT NULL;
-- Constraint: status_changed_at must be >= published_at
ALTER TABLE servers ADD CONSTRAINT check_status_changed_at_after_published
CHECK (status_changed_at >= published_at);
COMMIT;

View file

@ -79,6 +79,75 @@ func NewPostgreSQL(ctx context.Context, connectionURI string) (*PostgreSQL, erro
}, nil
}
// buildFilterConditions constructs WHERE clause conditions from a ServerFilter
//
//nolint:unparam // argIndex is always 1 currently but kept for API flexibility
func buildFilterConditions(filter *ServerFilter, argIndex int) ([]string, []any, int) {
var conditions []string
var args []any
if filter == nil {
return conditions, args, argIndex
}
if filter.Name != nil {
conditions = append(conditions, fmt.Sprintf("server_name = $%d", argIndex))
args = append(args, *filter.Name)
argIndex++
}
if filter.RemoteURL != nil {
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM jsonb_array_elements(value->'remotes') AS remote WHERE remote->>'url' = $%d)", argIndex))
args = append(args, *filter.RemoteURL)
argIndex++
}
if filter.UpdatedSince != nil {
conditions = append(conditions, fmt.Sprintf("updated_at > $%d", argIndex))
args = append(args, *filter.UpdatedSince)
argIndex++
}
if filter.SubstringName != nil {
conditions = append(conditions, fmt.Sprintf("server_name ILIKE $%d", argIndex))
args = append(args, "%"+*filter.SubstringName+"%")
argIndex++
}
if filter.Version != nil {
conditions = append(conditions, fmt.Sprintf("version = $%d", argIndex))
args = append(args, *filter.Version)
argIndex++
}
if filter.IsLatest != nil {
conditions = append(conditions, fmt.Sprintf("is_latest = $%d", argIndex))
args = append(args, *filter.IsLatest)
argIndex++
}
if filter.IncludeDeleted == nil || !*filter.IncludeDeleted {
conditions = append(conditions, "status != 'deleted'")
}
return conditions, args, argIndex
}
// addCursorCondition adds pagination cursor condition to WHERE clause
func addCursorCondition(cursor string, argIndex int) (string, []any, int) {
if cursor == "" {
return "", nil, argIndex
}
// Parse cursor format: "serverName:version"
parts := strings.SplitN(cursor, ":", 2)
if len(parts) == 2 {
cursorServerName := parts[0]
cursorVersion := parts[1]
// Use compound condition: (server_name > cursor_name) OR (server_name = cursor_name AND version > cursor_version)
condition := fmt.Sprintf("(server_name > $%d OR (server_name = $%d AND version > $%d))", argIndex, argIndex+1, argIndex+2)
return condition, []any{cursorServerName, cursorServerName, cursorVersion}, argIndex + 3
}
// Fallback for malformed cursor - treat as server name only for backwards compatibility
condition := fmt.Sprintf("server_name > $%d", argIndex)
return condition, []any{cursor}, argIndex + 1
}
func (db *PostgreSQL) ListServers(
ctx context.Context,
tx pgx.Tx,
@ -94,64 +163,17 @@ func (db *PostgreSQL) ListServers(
return nil, "", ctx.Err()
}
// Build WHERE clause for filtering using dedicated columns
var whereConditions []string
args := []any{}
// Build WHERE clause conditions
argIndex := 1
whereConditions, args, argIndex := buildFilterConditions(filter, argIndex)
// Add filters using dedicated columns for better performance
if filter != nil {
if filter.Name != nil {
whereConditions = append(whereConditions, fmt.Sprintf("server_name = $%d", argIndex))
args = append(args, *filter.Name)
argIndex++
}
if filter.RemoteURL != nil {
whereConditions = append(whereConditions, fmt.Sprintf("EXISTS (SELECT 1 FROM jsonb_array_elements(value->'remotes') AS remote WHERE remote->>'url' = $%d)", argIndex))
args = append(args, *filter.RemoteURL)
argIndex++
}
if filter.UpdatedSince != nil {
whereConditions = append(whereConditions, fmt.Sprintf("updated_at > $%d", argIndex))
args = append(args, *filter.UpdatedSince)
argIndex++
}
if filter.SubstringName != nil {
whereConditions = append(whereConditions, fmt.Sprintf("server_name ILIKE $%d", argIndex))
args = append(args, "%"+*filter.SubstringName+"%")
argIndex++
}
if filter.Version != nil {
whereConditions = append(whereConditions, fmt.Sprintf("version = $%d", argIndex))
args = append(args, *filter.Version)
argIndex++
}
if filter.IsLatest != nil {
whereConditions = append(whereConditions, fmt.Sprintf("is_latest = $%d", argIndex))
args = append(args, *filter.IsLatest)
argIndex++
}
}
// Add cursor pagination using compound serverName:version cursor
if cursor != "" {
// Parse cursor format: "serverName:version"
parts := strings.SplitN(cursor, ":", 2)
if len(parts) == 2 {
cursorServerName := parts[0]
cursorVersion := parts[1]
// Use compound condition: (server_name > cursor_name) OR (server_name = cursor_name AND version > cursor_version)
whereConditions = append(whereConditions, fmt.Sprintf("(server_name > $%d OR (server_name = $%d AND version > $%d))", argIndex, argIndex+1, argIndex+2))
args = append(args, cursorServerName, cursorServerName, cursorVersion)
argIndex += 3
} else {
// Fallback for malformed cursor - treat as server name only for backwards compatibility
whereConditions = append(whereConditions, fmt.Sprintf("server_name > $%d", argIndex))
args = append(args, cursor)
argIndex++
}
// Add cursor pagination
cursorCondition, cursorArgs, argIndex := addCursorCondition(cursor, argIndex)
if cursorCondition != "" {
whereConditions = append(whereConditions, cursorCondition)
args = append(args, cursorArgs...)
}
_ = argIndex // Silence unused variable warning
// Build the WHERE clause
whereClause := ""
@ -161,7 +183,7 @@ func (db *PostgreSQL) ListServers(
// Query servers table with hybrid column/JSON data
query := fmt.Sprintf(`
SELECT server_name, version, status, published_at, updated_at, is_latest, value
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
FROM servers
%s
ORDER BY server_name, version
@ -178,11 +200,12 @@ func (db *PostgreSQL) ListServers(
var results []*apiv0.ServerResponse
for rows.Next() {
var serverName, version, status string
var publishedAt, updatedAt time.Time
var statusChangedAt, publishedAt, updatedAt time.Time
var statusMessage *string
var isLatest bool
var valueJSON []byte
err := rows.Scan(&serverName, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
err := rows.Scan(&serverName, &version, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &valueJSON)
if err != nil {
return nil, "", fmt.Errorf("failed to scan server row: %w", err)
}
@ -198,10 +221,12 @@ func (db *PostgreSQL) ListServers(
Server: serverJSON,
Meta: apiv0.ResponseMeta{
Official: &apiv0.RegistryExtensions{
Status: model.Status(status),
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
Status: model.Status(status),
StatusChangedAt: statusChangedAt,
StatusMessage: statusMessage,
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
},
},
}
@ -224,25 +249,41 @@ func (db *PostgreSQL) ListServers(
}
// GetServerByName retrieves the latest version of a server by server name
func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error) {
func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName string, includeDeleted bool) (*apiv0.ServerResponse, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
query := `
SELECT server_name, version, status, published_at, updated_at, is_latest, value
// Build filter conditions
isLatest := true
filter := &ServerFilter{
Name: &serverName,
IsLatest: &isLatest,
IncludeDeleted: &includeDeleted,
}
argIndex := 1
whereConditions, args, _ := buildFilterConditions(filter, argIndex)
whereClause := ""
if len(whereConditions) > 0 {
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
}
query := fmt.Sprintf(`
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
FROM servers
WHERE server_name = $1 AND is_latest = true
%s
ORDER BY published_at DESC
LIMIT 1
`
`, whereClause)
var name, version, status string
var publishedAt, updatedAt time.Time
var isLatest bool
var statusChangedAt, publishedAt, updatedAt time.Time
var statusMessage *string
var valueJSON []byte
err := db.getExecutor(tx).QueryRow(ctx, query, serverName).Scan(&name, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
err := db.getExecutor(tx).QueryRow(ctx, query, args...).Scan(&name, &version, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &valueJSON)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
@ -261,10 +302,12 @@ func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName
Server: serverJSON,
Meta: apiv0.ResponseMeta{
Official: &apiv0.RegistryExtensions{
Status: model.Status(status),
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
Status: model.Status(status),
StatusChangedAt: statusChangedAt,
StatusMessage: statusMessage,
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
},
},
}
@ -273,24 +316,40 @@ func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName
}
// GetServerByNameAndVersion retrieves a specific version of a server by server name and version
func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string) (*apiv0.ServerResponse, error) {
func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string, includeDeleted bool) (*apiv0.ServerResponse, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
query := `
SELECT server_name, version, status, published_at, updated_at, is_latest, value
// Build filter conditions
filter := &ServerFilter{
Name: &serverName,
Version: &version,
IncludeDeleted: &includeDeleted,
}
argIndex := 1
whereConditions, args, _ := buildFilterConditions(filter, argIndex)
whereClause := ""
if len(whereConditions) > 0 {
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
}
query := fmt.Sprintf(`
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
FROM servers
WHERE server_name = $1 AND version = $2
%s
LIMIT 1
`
`, whereClause)
var name, vers, status string
var publishedAt, updatedAt time.Time
var statusChangedAt, publishedAt, updatedAt time.Time
var statusMessage *string
var isLatest bool
var valueJSON []byte
err := db.getExecutor(tx).QueryRow(ctx, query, serverName, version).Scan(&name, &vers, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
err := db.getExecutor(tx).QueryRow(ctx, query, args...).Scan(&name, &vers, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &valueJSON)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
@ -309,10 +368,12 @@ func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx,
Server: serverJSON,
Meta: apiv0.ResponseMeta{
Official: &apiv0.RegistryExtensions{
Status: model.Status(status),
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
Status: model.Status(status),
StatusChangedAt: statusChangedAt,
StatusMessage: statusMessage,
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
},
},
}
@ -321,19 +382,33 @@ func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx,
}
// GetAllVersionsByServerName retrieves all versions of a server by server name
func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string) ([]*apiv0.ServerResponse, error) {
func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string, includeDeleted bool) ([]*apiv0.ServerResponse, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
query := `
SELECT server_name, version, status, published_at, updated_at, is_latest, value
FROM servers
WHERE server_name = $1
ORDER BY published_at DESC
`
// Build filter conditions
filter := &ServerFilter{
Name: &serverName,
IncludeDeleted: &includeDeleted,
}
rows, err := db.getExecutor(tx).Query(ctx, query, serverName)
argIndex := 1
whereConditions, args, _ := buildFilterConditions(filter, argIndex)
whereClause := ""
if len(whereConditions) > 0 {
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
}
query := fmt.Sprintf(`
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
FROM servers
%s
ORDER BY published_at DESC
`, whereClause)
rows, err := db.getExecutor(tx).Query(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("failed to query server versions: %w", err)
}
@ -342,11 +417,12 @@ func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx,
var results []*apiv0.ServerResponse
for rows.Next() {
var name, version, status string
var publishedAt, updatedAt time.Time
var statusChangedAt, publishedAt, updatedAt time.Time
var statusMessage *string
var isLatest bool
var valueJSON []byte
err := rows.Scan(&name, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
err := rows.Scan(&name, &version, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &valueJSON)
if err != nil {
return nil, fmt.Errorf("failed to scan server row: %w", err)
}
@ -362,10 +438,12 @@ func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx,
Server: serverJSON,
Meta: apiv0.ResponseMeta{
Official: &apiv0.RegistryExtensions{
Status: model.Status(status),
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
Status: model.Status(status),
StatusChangedAt: statusChangedAt,
StatusMessage: statusMessage,
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
},
},
}
@ -407,20 +485,21 @@ func (db *PostgreSQL) CreateServer(ctx context.Context, tx pgx.Tx, serverJSON *a
// Insert the new server version using composite primary key
insertQuery := `
INSERT INTO servers (server_name, version, status, published_at, updated_at, is_latest, value)
VALUES ($1, $2, $3, $4, $5, $6, $7)
INSERT INTO servers (server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
`
_, err = db.getExecutor(tx).Exec(ctx, insertQuery,
serverJSON.Name,
serverJSON.Version,
string(officialMeta.Status),
officialMeta.StatusChangedAt,
officialMeta.StatusMessage,
officialMeta.PublishedAt,
officialMeta.UpdatedAt,
officialMeta.IsLatest,
valueJSON,
)
if err != nil {
return nil, fmt.Errorf("failed to insert server: %w", err)
}
@ -463,14 +542,15 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, tx pgx.Tx, serverName, v
UPDATE servers
SET value = $1, updated_at = NOW()
WHERE server_name = $2 AND version = $3
RETURNING server_name, version, status, published_at, updated_at, is_latest
RETURNING server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest
`
var name, vers, status string
var publishedAt, updatedAt time.Time
var statusChangedAt, publishedAt, updatedAt time.Time
var statusMessage *string
var isLatest bool
err = db.getExecutor(tx).QueryRow(ctx, query, valueJSON, serverName, version).Scan(&name, &vers, &status, &publishedAt, &updatedAt, &isLatest)
err = db.getExecutor(tx).QueryRow(ctx, query, valueJSON, serverName, version).Scan(&name, &vers, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
@ -483,10 +563,12 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, tx pgx.Tx, serverName, v
Server: *serverJSON,
Meta: apiv0.ResponseMeta{
Official: &apiv0.RegistryExtensions{
Status: model.Status(status),
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
Status: model.Status(status),
StatusChangedAt: statusChangedAt,
StatusMessage: statusMessage,
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
},
},
}
@ -495,25 +577,31 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, tx pgx.Tx, serverName, v
}
// SetServerStatus updates the status of a specific server version
func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status string) (*apiv0.ServerResponse, error) {
func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status model.Status, statusMessage *string) (*apiv0.ServerResponse, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Update the status column
// Update the status and related fields
// Only update status_changed_at when status actually changes
query := `
UPDATE servers
SET status = $1, updated_at = NOW()
SET
status = $1,
status_changed_at = CASE WHEN status != $1::varchar THEN NOW() ELSE status_changed_at END,
updated_at = NOW(),
status_message = $4
WHERE server_name = $2 AND version = $3
RETURNING server_name, version, status, value, published_at, updated_at, is_latest
RETURNING server_name, version, status, value, published_at, updated_at, is_latest, status_changed_at, status_message
`
var name, vers, currentStatus string
var publishedAt, updatedAt time.Time
var publishedAt, updatedAt, statusChangedAt time.Time
var isLatest bool
var valueJSON []byte
var resultStatusMessage *string
err := db.getExecutor(tx).QueryRow(ctx, query, status, serverName, version).Scan(&name, &vers, &currentStatus, &valueJSON, &publishedAt, &updatedAt, &isLatest)
err := db.getExecutor(tx).QueryRow(ctx, query, string(status), serverName, version, statusMessage).Scan(&name, &vers, &currentStatus, &valueJSON, &publishedAt, &updatedAt, &isLatest, &statusChangedAt, &resultStatusMessage)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
@ -532,10 +620,12 @@ func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName
Server: serverJSON,
Meta: apiv0.ResponseMeta{
Official: &apiv0.RegistryExtensions{
Status: model.Status(currentStatus),
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
Status: model.Status(currentStatus),
StatusChangedAt: statusChangedAt,
StatusMessage: resultStatusMessage,
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
},
},
}
@ -543,6 +633,78 @@ func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName
return serverResponse, nil
}
// SetAllVersionsStatus updates the status of all versions of a server in a single query
func (db *PostgreSQL) SetAllVersionsStatus(ctx context.Context, tx pgx.Tx, serverName string, status model.Status, statusMessage *string) ([]*apiv0.ServerResponse, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Update the status and related fields for all versions
// Only update rows where status or status_message actually changes
// Only update status_changed_at when status actually changes
query := `
UPDATE servers
SET
status = $1,
status_changed_at = CASE WHEN status != $1::varchar THEN NOW() ELSE status_changed_at END,
updated_at = NOW(),
status_message = $2
WHERE server_name = $3
AND (status != $1::varchar OR status_message IS DISTINCT FROM $2)
RETURNING server_name, version, status, value, published_at, updated_at, is_latest, status_changed_at, status_message
`
rows, err := db.getExecutor(tx).Query(ctx, query, string(status), statusMessage, serverName)
if err != nil {
return nil, fmt.Errorf("failed to update all server versions status: %w", err)
}
defer rows.Close()
var results []*apiv0.ServerResponse
for rows.Next() {
var name, vers, currentStatus string
var publishedAt, updatedAt, statusChangedAt time.Time
var isLatest bool
var valueJSON []byte
var resultStatusMessage *string
if err := rows.Scan(&name, &vers, &currentStatus, &valueJSON, &publishedAt, &updatedAt, &isLatest, &statusChangedAt, &resultStatusMessage); err != nil {
return nil, fmt.Errorf("failed to scan server row: %w", err)
}
// Unmarshal the JSON data
var serverJSON apiv0.ServerJSON
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
}
serverResponse := &apiv0.ServerResponse{
Server: serverJSON,
Meta: apiv0.ResponseMeta{
Official: &apiv0.RegistryExtensions{
Status: model.Status(currentStatus),
StatusChangedAt: statusChangedAt,
StatusMessage: resultStatusMessage,
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
},
},
}
results = append(results, serverResponse)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating server rows: %w", err)
}
if len(results) == 0 {
return nil, ErrNotFound
}
return results, nil
}
// InTransaction executes a function within a database transaction
func (db *PostgreSQL) InTransaction(ctx context.Context, fn func(ctx context.Context, tx pgx.Tx) error) error {
if ctx.Err() != nil {
@ -615,7 +777,7 @@ func (db *PostgreSQL) GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, se
executor := db.getExecutor(tx)
query := `
SELECT server_name, version, status, value, published_at, updated_at, is_latest
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
FROM servers
WHERE server_name = $1 AND is_latest = true
`
@ -623,11 +785,12 @@ func (db *PostgreSQL) GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, se
row := executor.QueryRow(ctx, query, serverName)
var name, version, status string
var publishedAt, updatedAt time.Time
var statusChangedAt, publishedAt, updatedAt time.Time
var statusMessage *string
var isLatest bool
var jsonValue []byte
err := row.Scan(&name, &version, &status, &jsonValue, &publishedAt, &updatedAt, &isLatest)
err := row.Scan(&name, &version, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &jsonValue)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
@ -646,9 +809,12 @@ func (db *PostgreSQL) GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, se
Server: serverJSON,
Meta: apiv0.ResponseMeta{
Official: &apiv0.RegistryExtensions{
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
Status: model.Status(status),
StatusChangedAt: statusChangedAt,
StatusMessage: statusMessage,
PublishedAt: publishedAt,
UpdatedAt: updatedAt,
IsLatest: isLatest,
},
},
}

File diff suppressed because it is too large Load diff