refactor(payment): 支付插件 - 宿主仅通过 RPC 包加载并保护订单版本

This commit is contained in:
ddCat committed 2026-09-02 16:15:57 +08:00
1 parent d6bbdbe27b
commit 38e715ea3f
45 files changed
+1584 -203

No files matched your search

+44 -17
View File
@@ -107,6 +107,44 @@ type AdminPaymentOrderPage struct {
Limit int `json:"limit"`
}
func (s *Service) PaymentNotificationResponse(providerID string, success bool) (int, string, string) {
return PaymentNotificationResponseForWithRegistry(s.paymentRegistry, providerID, success, http.StatusInternalServerError)
}
func (s *Service) PaymentNotificationFailureResponse(providerID string, status int) (int, string, string) {
return PaymentNotificationResponseForWithRegistry(s.paymentRegistry, providerID, false, status)
}
func PaymentNotificationResponseFor(providerID string, success bool, failureStatus int) (int, string, string) {
registry, _ := payment.NewRegistry()
return PaymentNotificationResponseForWithRegistry(registry, providerID, success, failureStatus)
}
func PaymentNotificationResponseForWithRegistry(registry *payment.Registry, providerID string, success bool, failureStatus int) (int, string, string) {
if registry != nil {
if provider, ok := registry.Get(providerID); ok {
descriptor := provider.Descriptor()
response := descriptor.NotificationFailure
if success {
response = descriptor.NotificationSuccess
}
status := response.Status
if status == 0 {
status = failureStatus
}
contentType, body := response.ContentType, response.Body
if contentType == "" {
contentType = "text/plain; charset=utf-8"
}
return status, contentType, body
}
}
if success {
return http.StatusNoContent, "", ""
}
return failureStatus, "", ""
}
func (s *Service) PaymentProviders(actor *model.User) ([]PaymentProviderView, error) {
if actor == nil {
return nil, Unauthorized("请先登录")
@@ -186,7 +224,7 @@ func (s *Service) UpdatePaymentProviderConfig(actor *model.User, providerID stri
if err != nil {
return nil, err
}
for _, field := range paymentProviderIdentityFields(providerID) {
for _, field := range descriptor.IdentityFields {
previousIdentity[field] = strings.TrimSpace(values[field])
}
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
@@ -242,7 +280,7 @@ func (s *Service) UpdatePaymentProviderConfig(actor *model.User, providerID stri
}
digest := sha256.Sum256(plain)
config := &model.PaymentProviderConfig{
ID: newID(), ProviderID: descriptor.ID, PluginID: descriptor.PluginID,
ID: newID(), ProviderID: descriptor.ID, PluginID: descriptor.PluginID, PluginVersion: descriptor.PluginVersion,
Enabled: request.Enabled, CloseAfterMinutes: request.CloseAfterMinutes,
ConfigCipher: ciphertext, ConfigDigest: hex.EncodeToString(digest[:]), CreatedBy: actor.ID,
}
@@ -266,17 +304,6 @@ func (s *Service) UpdatePaymentProviderConfig(actor *model.User, providerID stri
return nil, errors.New("保存支付渠道配置后未找到渠道")
}
func paymentProviderIdentityFields(providerID string) []string {
switch strings.TrimSpace(providerID) {
case PaymentProviderWeChat:
return []string{"appId", "mchId"}
case PaymentProviderAlipay:
return []string{"appId", "sellerId"}
default:
return nil
}
}
func (s *Service) paymentProviderView(descriptor payment.Descriptor) (PaymentProviderView, *model.PaymentProviderConfig, error) {
view := PaymentProviderView{ID: descriptor.ID, PluginID: descriptor.PluginID, Name: descriptor.Name, Icon: descriptor.Icon, CheckoutMode: descriptor.CheckoutMode}
if manifest, ok := paymentManifestForProvider(descriptor.ID); ok && len(manifest.Contributes.PaymentProviders) > 0 {
@@ -457,7 +484,7 @@ func (s *Service) CreatePaymentOrder(ctx context.Context, actor *model.User, req
order := &model.PaymentOrder{
ID: newID(), UserID: actor.ID, IdempotencyKey: idempotencyKey, MerchantOrderNo: newID(),
ProductID: product.ID, ProductName: product.Name, ProviderID: provider.Descriptor().ID,
PluginID: provider.Descriptor().PluginID, ProviderConfigID: config.ID, ProviderConfigVersion: config.Version,
PluginID: provider.Descriptor().PluginID, PluginVersion: provider.Descriptor().PluginVersion, ProviderConfigID: config.ID, ProviderConfigVersion: config.Version,
AmountFen: product.AmountFen, Currency: "CNY", CreditsMicrocredits: product.CreditsMicrocredits,
Status: model.PaymentOrderCreated, CheckoutMode: provider.Descriptor().CheckoutMode,
ExpiresAt: now.Add(time.Duration(config.CloseAfterMinutes) * time.Minute),
@@ -480,7 +507,7 @@ func (s *Service) CreatePaymentOrder(ctx context.Context, actor *model.User, req
MerchantOrderNo: order.MerchantOrderNo, Description: product.Name, AmountFen: order.AmountFen,
Currency: order.Currency, ExpiresAt: order.ExpiresAt,
NotifyURL: baseURL + "/api/payments/notify/" + url.PathEscape(order.ProviderID) + "/" + url.PathEscape(config.ID),
ReturnURL: baseURL + "/api/payments/return/alipay?orderId=" + url.QueryEscape(order.ID),
ReturnURL: baseURL + "/api/payments/return/" + url.PathEscape(order.ProviderID) + "?orderId=" + url.QueryEscape(order.ID),
})
if err != nil {
_ = s.repo.SetPaymentOrderCreateFailure(order.ID, safePaymentError(err))
@@ -564,7 +591,7 @@ func (s *Service) RefreshPaymentCheckout(ctx context.Context, actor *model.User,
MerchantOrderNo: order.MerchantOrderNo, Description: order.ProductName, AmountFen: order.AmountFen,
Currency: order.Currency, ExpiresAt: order.ExpiresAt,
NotifyURL: baseURL + "/api/payments/notify/" + url.PathEscape(order.ProviderID) + "/" + url.PathEscape(config.ID),
ReturnURL: baseURL + "/api/payments/return/alipay?orderId=" + url.QueryEscape(order.ID),
ReturnURL: baseURL + "/api/payments/return/" + url.PathEscape(order.ProviderID) + "?orderId=" + url.QueryEscape(order.ID),
})
if err != nil {
return nil, WrapAppError(http.StatusBadGateway, "刷新支付收银台失败,请稍后重试", err)
@@ -810,7 +837,7 @@ func (s *Service) paymentRuntimeForOrder(order *model.PaymentOrder) (payment.Pro
if err != nil {
return nil, nil, nil, err
}
if config.ProviderID != order.ProviderID || config.PluginID != order.PluginID || config.Version != order.ProviderConfigVersion {
if config.ProviderID != order.ProviderID || config.PluginID != order.PluginID || (config.PluginVersion != "" && order.PluginVersion != "" && config.PluginVersion != order.PluginVersion) || config.Version != order.ProviderConfigVersion {
return nil, nil, nil, repository.ErrPaymentOrderStateConflict
}
values, err := s.decryptPaymentConfig(config)
@@ -0,0 +1,56 @@
package service
import (
"encoding/json"
"strings"
"testing"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/protocol"
"infinite-canvas/backend/internal/repository"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newPaymentLifecycleService(t *testing.T, status model.PaymentOrderStatus) (*Service, protocol.Manifest) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:"+newID()+"?mode=memory&cache=shared"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.PaymentOrder{}); err != nil {
t.Fatal(err)
}
manifest := bundledPaymentPluginManifests()[0]
manifest.Metadata.ID = "uploaded-payment"
manifest.Metadata.Version = "1.0.0"
manifest.Metadata.Enabled = true
raw, err := json.Marshal(manifest)
if err != nil {
t.Fatal(err)
}
center := &pluginRuntime{plugins: map[string]pluginRecord{
manifest.Metadata.ID: {Raw: raw, Metadata: manifest.Metadata, Source: PluginOriginUploaded},
}}
order := model.PaymentOrder{ID: "active-order", UserID: "user", IdempotencyKey: "key", MerchantOrderNo: "merchant", ProviderID: manifest.Contributes.PaymentProviders[0].ID, PluginID: manifest.Metadata.ID, PluginVersion: manifest.Metadata.Version, Status: status}
if err := db.Create(&order).Error; err != nil {
t.Fatal(err)
}
return &Service{repo: repository.New(db), pluginRuntime: center}, manifest
}
func TestPaymentPluginUpgradeBlockedByActiveOrders(t *testing.T) {
svc, next := newPaymentLifecycleService(t, model.PaymentOrderPending)
next.Metadata.Version = "2.0.0"
if err := svc.ensurePaymentPluginLifecycle(next); err == nil || !strings.Contains(err.Error(), "未完成订单") {
t.Fatalf("upgrade guard error = %v", err)
}
}
func TestPaymentPluginRemovalAllowedAfterOrdersFinish(t *testing.T) {
svc, manifest := newPaymentLifecycleService(t, model.PaymentOrderCredited)
if err := svc.ensurePaymentPluginCanBeRemoved(manifest.Metadata.ID); err != nil {
t.Fatalf("removal guard rejected completed order: %v", err)
}
}
+31 -5
View File
@@ -1,15 +1,14 @@
package service
import (
"infinite-canvas/backend/internal/payment"
"infinite-canvas/backend/internal/protocol"
)
const (
PaymentPluginWeChatNative = payment.PluginWeChatNative
PaymentPluginAlipayPage = payment.PluginAlipayPage
PaymentProviderWeChat = payment.ProviderWeChatNative
PaymentProviderAlipay = payment.ProviderAlipayPage
PaymentPluginWeChatNative = "official-payment-wechat-native"
PaymentPluginAlipayPage = "official-payment-alipay-page"
PaymentProviderWeChat = "wechat-native"
PaymentProviderAlipay = "alipay-page-pay"
)
func bundledPaymentPluginManifests() []protocol.Manifest {
@@ -53,11 +52,38 @@ func paymentPluginManifest(pluginID, providerID, name, vendor, description, runt
Configuration: configuration,
Contributes: protocol.ManifestContributions{PaymentProviders: []protocol.ManifestPaymentProvider{{
ID: providerID, Label: name, Icon: icon, CheckoutMode: checkoutMode,
IdentityFields: paymentIdentityFields(providerID),
NotificationSuccess: paymentNotificationSuccess(providerID), NotificationFailure: paymentNotificationFailure(providerID),
ExpiryPolicy: protocol.ManifestPaymentExpiryPolicy{DefaultMinutes: 30, MinMinutes: 5, MaxMinutes: 1440},
}}},
}
}
func paymentIdentityFields(providerID string) []string {
switch providerID {
case PaymentProviderWeChat:
return []string{"appId", "mchId"}
case PaymentProviderAlipay:
return []string{"appId", "sellerId"}
default:
return nil
}
}
func paymentNotificationSuccess(providerID string) protocol.ManifestPaymentResponse {
if providerID == PaymentProviderAlipay {
return protocol.ManifestPaymentResponse{Status: 200, ContentType: "text/plain; charset=utf-8", Body: "success"}
}
return protocol.ManifestPaymentResponse{Status: 204}
}
func paymentNotificationFailure(providerID string) protocol.ManifestPaymentResponse {
if providerID == PaymentProviderAlipay {
return protocol.ManifestPaymentResponse{Status: 400, ContentType: "text/plain; charset=utf-8", Body: "failure"}
}
return protocol.ManifestPaymentResponse{Status: 400}
}
func wechatPaymentConfiguration() protocol.ManifestConfiguration {
return protocol.ManifestConfiguration{Fields: []protocol.ManifestField{
{Name: "publicBaseUrl", Type: "url", Label: "服务器公网地址", Required: true, Description: "用于生成微信支付回调地址,必须可被微信访问。"},
@@ -8,7 +8,6 @@ import (
)
func TestBundledPaymentPluginsMatchHostProviders(t *testing.T) {
registry := payment.Builtins()
manifests := bundledPaymentPluginManifests()
if len(manifests) != 2 {
t.Fatalf("payment plugin manifests = %d", len(manifests))
@@ -25,13 +24,8 @@ func TestBundledPaymentPluginsMatchHostProviders(t *testing.T) {
t.Fatalf("plugin %s payment contributions = %d", manifest.Metadata.ID, len(manifest.Contributes.PaymentProviders))
}
contribution := manifest.Contributes.PaymentProviders[0]
provider, ok := registry.Get(contribution.ID)
if !ok {
t.Fatalf("plugin %s has no host provider %s", manifest.Metadata.ID, contribution.ID)
}
descriptor := provider.Descriptor()
if descriptor.PluginID != manifest.Metadata.ID || descriptor.Icon != contribution.Icon || descriptor.CheckoutMode != contribution.CheckoutMode {
t.Fatalf("plugin/provider mismatch: manifest=%#v descriptor=%#v", contribution, descriptor)
if contribution.ID == "" || contribution.Icon == "" || contribution.CheckoutMode == "" {
t.Fatalf("plugin %s has incomplete payment contribution: %#v", manifest.Metadata.ID, contribution)
}
}
}
@@ -56,6 +50,51 @@ func TestBundledPaymentPluginsLoadFromSystemSource(t *testing.T) {
}
}
func TestSystemPaymentPluginsRegisterRPCProviders(t *testing.T) {
center, err := newPluginRuntime(t.TempDir())
if err != nil {
t.Fatal(err)
}
registry := center.paymentRegistrySnapshot()
if registry == nil {
t.Fatal("payment registry is nil")
}
for _, providerID := range []string{PaymentProviderAlipay, PaymentProviderWeChat} {
provider, ok := registry.Get(providerID)
if !ok {
t.Fatalf("payment provider %q is missing", providerID)
}
if _, ok := provider.(*payment.RPCProvider); !ok {
t.Fatalf("payment provider %q has type %T, want *payment.RPCProvider", providerID, provider)
}
if provider.Descriptor().PluginID == "" || provider.Descriptor().PluginVersion == "" {
t.Fatalf("payment provider %q is missing plugin identity: %#v", providerID, provider.Descriptor())
}
}
}
func TestPaymentRegistryFailsClosedWhenOfficialPackagesAreMissing(t *testing.T) {
t.Setenv("CANVAS_OFFICIAL_PLUGIN_DIR", t.TempDir())
center, err := newPluginRuntime(t.TempDir())
if err != nil {
t.Fatal(err)
}
registry := center.paymentRegistrySnapshot()
if registry == nil {
t.Fatal("payment registry is nil")
}
for _, providerID := range []string{PaymentProviderAlipay, PaymentProviderWeChat} {
if _, ok := registry.Get(providerID); ok {
t.Fatalf("payment provider %q unexpectedly came from host fallback", providerID)
}
}
for _, plugin := range center.list() {
if plugin.Management.Kind == PluginKindPayment && plugin.Status != "invalid" {
t.Fatalf("missing package payment plugin %q status = %q, want invalid", plugin.Manifest.ID, plugin.Status)
}
}
}
func TestTopupProductCreditAmountStaysWithinSafeLimit(t *testing.T) {
if _, err := topupProductFromRequest("product", "admin", TopupProductRequest{
Name: "过大积分商品", AmountFen: 1, CreditsMicrocredits: maxTopupCreditsMicrocredits + 1,
+142 -18
View File
@@ -13,6 +13,7 @@ import (
"sync"
"time"
"infinite-canvas/backend/internal/payment"
"infinite-canvas/backend/internal/protocol"
)
@@ -66,12 +67,13 @@ type pluginRecord struct {
}
type pluginRuntime struct {
mu sync.RWMutex
mutationMu sync.Mutex
registryPath string
packageDir string
plugins map[string]pluginRecord
registry *protocol.Registry
mu sync.RWMutex
mutationMu sync.Mutex
registryPath string
packageDir string
plugins map[string]pluginRecord
registry *protocol.Registry
paymentRegistry *payment.Registry
}
type pluginRegistryRecord struct {
@@ -136,8 +138,10 @@ func (c *pluginRuntime) bootstrapBuiltInPlugins() error {
if strings.HasPrefix(strings.TrimSpace(pkg.Manifest.Runtime.Backend), "host:") {
return fmt.Errorf("官方插件 %q 不能依赖 host 执行器", pkg.Manifest.Metadata.ID)
}
if _, err := protocol.LoadInstalledProviders(pkg.ManifestRaw, nil); err != nil {
return fmt.Errorf("加载官方插件 %q:%w", pkg.Manifest.Metadata.ID, err)
if len(pkg.Manifest.Contributes.PaymentProviders) == 0 {
if _, err := protocol.LoadInstalledProviders(pkg.ManifestRaw, nil); err != nil {
return fmt.Errorf("加载官方插件 %q:%w", pkg.Manifest.Metadata.ID, err)
}
}
id := pkg.Manifest.Metadata.ID
if _, duplicate := builtInIDs[id]; duplicate {
@@ -165,13 +169,22 @@ func (c *pluginRuntime) bootstrapBuiltInPlugins() error {
if record.InstalledAt.IsZero() {
record.InstalledAt = now
}
record.ID, record.Raw, record.Source, record.FileName = id, manifestData, PluginOriginOfficial, entry.Name()
source := PluginOriginOfficial
if _, systemPayment := systemPaymentPolicies[id]; systemPayment {
source = PluginOriginSystem
}
record.ID, record.Raw, record.Source, record.FileName = id, manifestData, source, entry.Name()
record.PackagePath, record.PackageSHA256, record.UpdatedAt = packageName, hash, now
byID[id] = record
}
bundledManifests := append(bundledWorkflowPluginManifests(), bundledPaymentPluginManifests()...)
for _, bundled := range bundledManifests {
builtInIDs[bundled.Metadata.ID] = struct{}{}
if existing, exists := byID[bundled.Metadata.ID]; exists && existing.PackagePath != "" && isSystemPaymentPluginID(bundled.Metadata.ID) {
// An official package is the executable source of truth. The bundled
// manifest remains only as a fallback when the package is unavailable.
continue
}
data, err := json.Marshal(bundled)
if err != nil {
return fmt.Errorf("encode built-in plugin %s: %w", bundled.Metadata.ID, err)
@@ -215,6 +228,11 @@ func (c *pluginRuntime) bootstrapBuiltInPlugins() error {
return c.writeRegistry(result)
}
func isSystemPaymentPluginID(id string) bool {
_, ok := systemPaymentPolicies[strings.TrimSpace(id)]
return ok
}
func isBuiltInPluginSource(source string) bool {
switch strings.TrimSpace(source) {
case "bundled", PluginOriginOfficial, PluginOriginSystem:
@@ -295,15 +313,22 @@ func (c *pluginRuntime) reload() error {
plugins[id] = record
continue
}
if len(manifest.Contributes.PaymentProviders) > 0 {
_, systemPayment := systemPaymentPolicies[id]
if record.Source != PluginOriginSystem || !systemPayment {
if len(manifest.Contributes.PaymentProviders) > 0 && record.Source == PluginOriginUploaded {
backend := strings.TrimSpace(manifest.Runtime.Backend)
if strings.HasPrefix(backend, "host:") {
record.Metadata.Enabled = false
record.Status = "invalid"
record.Error = "首期支付插件只能使用系统宿主适配器"
plugins[id] = record
continue
}
if backend != "rpc" && backend != "wasm" {
record.Metadata.Enabled = false
record.Status = "invalid"
record.Error = "上传支付插件必须声明 rpc 或 wasm 后端"
plugins[id] = record
continue
}
}
if len(manifest.Contributes.PaymentProviders) > 0 && len(manifest.Contributes.Providers) == 0 {
if record.Metadata.Enabled {
@@ -349,9 +374,98 @@ func (c *pluginRuntime) reload() error {
}
c.plugins = plugins
c.registry = registry
// Payment adapters are loaded exclusively from validated plugin packages.
// An empty registry is intentional when the official package is unavailable;
// payment writes must fail closed instead of silently using host code.
basePayment, registryErr := payment.NewRegistry()
if registryErr != nil {
return registryErr
}
dynamicPayments := make([]payment.Provider, 0)
for id, record := range plugins {
if (record.Source != PluginOriginUploaded && record.Source != PluginOriginOfficial && record.Source != PluginOriginSystem) || !record.Metadata.Enabled || record.Status != "enabled" {
continue
}
var manifest protocol.Manifest
if err := json.Unmarshal(record.Raw, &manifest); err != nil || len(manifest.Contributes.PaymentProviders) == 0 {
continue
}
if strings.TrimSpace(manifest.Runtime.Backend) != "rpc" {
record.Status = "invalid"
record.Error = "wasm 支付运行时尚未启用"
plugins[id] = record
continue
}
packageData, readErr := os.ReadFile(filepath.Join(c.packageDir, filepath.Base(record.PackagePath)))
if readErr != nil {
record.Status = "invalid"
record.Error = "支付插件包文件不存在"
plugins[id] = record
continue
}
pkg, parseErr := protocol.ParsePluginPackage(packageData)
if parseErr != nil {
record.Status = "invalid"
record.Error = parseErr.Error()
plugins[id] = record
continue
}
runtimeDir, materializeErr := materializePaymentBackend(c.packageDir, record.PackageSHA256, pkg)
if materializeErr != nil {
record.Status = "invalid"
record.Error = materializeErr.Error()
plugins[id] = record
continue
}
for _, contribution := range manifest.Contributes.PaymentProviders {
provider, providerErr := payment.NewRPCProvider(payment.DescriptorFromManifest(manifest, contribution), runtimeDir, manifest.Runtime.BackendEntry)
if providerErr != nil {
record.Status = "invalid"
record.Error = providerErr.Error()
continue
}
dynamicPayments = append(dynamicPayments, provider)
}
}
dynamicIDs := make(map[string]struct{}, len(dynamicPayments))
for _, provider := range dynamicPayments {
dynamicIDs[provider.Descriptor().ID] = struct{}{}
}
baseProviders := make([]payment.Provider, 0)
for _, provider := range basePayment.Providers() {
if _, replaced := dynamicIDs[provider.Descriptor().ID]; !replaced {
baseProviders = append(baseProviders, provider)
}
}
providers := append(baseProviders, dynamicPayments...)
c.paymentRegistry, err = payment.NewRegistry(providers...)
if err != nil {
return err
}
c.plugins = plugins
return nil
}
func materializePaymentBackend(packageDir, hash string, pkg protocol.PluginPackage) (string, error) {
root := filepath.Join(packageDir, "runtime", strings.TrimSpace(hash))
if err := os.MkdirAll(root, 0o700); err != nil {
return "", fmt.Errorf("创建支付插件运行目录失败:%w", err)
}
for name, content := range pkg.Files {
if !strings.HasPrefix(name, "backend/") || strings.HasSuffix(name, "/") {
continue
}
target := filepath.Join(root, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return "", err
}
if err := os.WriteFile(target, content, 0o700); err != nil {
return "", fmt.Errorf("写入支付插件运行文件失败:%w", err)
}
}
return root, nil
}
func (c *pluginRuntime) list() []PluginView {
c.mu.RLock()
defer c.mu.RUnlock()
@@ -369,6 +483,12 @@ func (c *pluginRuntime) registrySnapshot() *protocol.Registry {
return c.registry
}
func (c *pluginRuntime) paymentRegistrySnapshot() *payment.Registry {
c.mu.RLock()
defer c.mu.RUnlock()
return c.paymentRegistry
}
func (c *pluginRuntime) install(data []byte, fileName string) (PluginView, error) {
c.mutationMu.Lock()
defer c.mutationMu.Unlock()
@@ -380,19 +500,18 @@ func (c *pluginRuntime) install(data []byte, fileName string) (PluginView, error
return PluginView{}, err
}
manifest := pkg.Manifest
if len(manifest.Contributes.PaymentProviders) > 0 {
return PluginView{}, errors.New("首期支付插件只能使用系统宿主适配器")
}
if strings.HasPrefix(strings.TrimSpace(manifest.Runtime.Backend), "host:") {
return PluginView{}, errors.New("上传插件不能使用宿主内置执行器")
}
if _, err := protocol.LoadInstalledProviders(pkg.ManifestRaw, nil); err != nil {
return PluginView{}, err
if len(manifest.Contributes.PaymentProviders) == 0 {
if _, err := protocol.LoadInstalledProviders(pkg.ManifestRaw, nil); err != nil {
return PluginView{}, err
}
}
c.mu.RLock()
existing, exists := c.plugins[manifest.Metadata.ID]
c.mu.RUnlock()
if exists && isBuiltInPluginSource(existing.Source) {
if exists && isBuiltInPluginSource(existing.Source) && !isPaymentPluginManifest(manifest) {
return PluginView{}, fmt.Errorf("内置插件 %q 不能通过上传覆盖", manifest.Metadata.ID)
}
manifest.Metadata.Enabled = !exists || existing.Metadata.Enabled
@@ -449,6 +568,11 @@ func (c *pluginRuntime) install(data []byte, fileName string) (PluginView, error
return PluginView{}, errors.New("插件保存后未加载")
}
func isPaymentPluginManifest(manifest protocol.Manifest) bool {
backend := strings.TrimSpace(manifest.Runtime.Backend)
return len(manifest.Contributes.PaymentProviders) > 0 && (backend == "rpc" || backend == "wasm")
}
func (c *pluginRuntime) setEnabled(id string, enabled bool) (PluginView, error) {
c.mutationMu.Lock()
defer c.mutationMu.Unlock()
+92 -4
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
@@ -251,7 +252,18 @@ func (s *Service) InstallPlugin(data []byte, fileName string) (PluginView, error
if s.pluginRuntime == nil {
return PluginView{}, fmt.Errorf("插件运行时未初始化")
}
return s.pluginRuntime.install(data, fileName)
parsed, err := protocol.ParsePluginPackage(data)
if err != nil {
return PluginView{}, err
}
if err := s.ensurePaymentPluginLifecycle(parsed.Manifest); err != nil {
return PluginView{}, err
}
plugin, err := s.pluginRuntime.install(data, fileName)
if err == nil {
s.refreshPaymentRegistry()
}
return plugin, err
}
func (s *Service) InstallPluginForAdmin(actor *model.User, data []byte, fileName string) (PluginView, error) {
@@ -265,7 +277,7 @@ func (s *Service) InstallPluginForAdmin(actor *model.User, data []byte, fileName
if _, reserved := officialApplicationPolicies[parsed.Manifest.Metadata.ID]; reserved {
return PluginView{}, fmt.Errorf("插件 ID %q 由官方应用保留", parsed.Manifest.Metadata.ID)
}
if _, reserved := systemPaymentPolicies[parsed.Manifest.Metadata.ID]; reserved {
if _, reserved := systemPaymentPolicies[parsed.Manifest.Metadata.ID]; reserved && !isPaymentPluginManifest(parsed.Manifest) {
return PluginView{}, fmt.Errorf("插件 ID %q 由系统支付插件保留", parsed.Manifest.Metadata.ID)
}
plugin, err := s.InstallPlugin(data, fileName)
@@ -308,14 +320,90 @@ func (s *Service) SetPluginEnabled(id string, enabled bool) (PluginView, error)
if s.pluginRuntime == nil {
return PluginView{}, fmt.Errorf("插件运行时未初始化")
}
return s.pluginRuntime.setEnabled(id, enabled)
plugin, err := s.pluginRuntime.setEnabled(id, enabled)
if err == nil {
s.refreshPaymentRegistry()
}
return plugin, err
}
func (s *Service) UninstallPlugin(id string) error {
if s.pluginRuntime == nil {
return fmt.Errorf("插件运行时未初始化")
}
return s.pluginRuntime.uninstall(id)
if err := s.ensurePaymentPluginCanBeRemoved(id); err != nil {
return err
}
err := s.pluginRuntime.uninstall(id)
if err == nil {
s.refreshPaymentRegistry()
}
return err
}
func (s *Service) ensurePaymentPluginLifecycle(next protocol.Manifest) error {
if s.repo == nil || s.pluginRuntime == nil || len(next.Contributes.PaymentProviders) == 0 {
return nil
}
s.pluginRuntime.mu.RLock()
current, exists := s.pluginRuntime.plugins[next.Metadata.ID]
s.pluginRuntime.mu.RUnlock()
if !exists {
return nil
}
var currentManifest protocol.Manifest
if err := json.Unmarshal(current.Raw, &currentManifest); err != nil {
return fmt.Errorf("读取现有插件 %q:%w", next.Metadata.ID, err)
}
if len(currentManifest.Contributes.PaymentProviders) == 0 || strings.TrimSpace(currentManifest.Metadata.Version) == strings.TrimSpace(next.Metadata.Version) {
return nil
}
count, err := s.repo.ActivePaymentOrderCountForPlugin(currentManifest.Metadata.ID, currentManifest.Metadata.Version)
if err != nil {
return fmt.Errorf("检查插件 %q 未完成订单:%w", current.Metadata.ID, err)
}
if count > 0 {
return fmt.Errorf("支付插件 %q 仍有 %d 个未完成订单,暂不能升级", current.Metadata.ID, count)
}
return nil
}
func (s *Service) ensurePaymentPluginCanBeRemoved(id string) error {
if s.repo == nil || s.pluginRuntime == nil {
return nil
}
s.pluginRuntime.mu.RLock()
record, exists := s.pluginRuntime.plugins[strings.TrimSpace(id)]
s.pluginRuntime.mu.RUnlock()
if !exists {
return nil
}
var manifest protocol.Manifest
if err := json.Unmarshal(record.Raw, &manifest); err != nil {
return fmt.Errorf("读取插件 %q:%w", id, err)
}
if len(manifest.Contributes.PaymentProviders) == 0 {
return nil
}
count, err := s.repo.ActivePaymentOrderCountForPlugin(manifest.Metadata.ID, "")
if err != nil {
return fmt.Errorf("检查插件 %q 未完成订单:%w", id, err)
}
if count > 0 {
return fmt.Errorf("支付插件 %q 仍有 %d 个未完成订单,暂不能卸载", id, count)
}
return nil
}
func (s *Service) refreshPaymentRegistry() {
if s.pluginRuntime == nil {
return
}
if registry := s.pluginRuntime.paymentRegistrySnapshot(); registry != nil {
s.registrationMu.Lock()
s.paymentRegistry = registry
s.registrationMu.Unlock()
}
}
func (s *Service) UninstallPluginForAdmin(actor *model.User, id string) error {
@@ -29,7 +29,24 @@ func TestPluginViewIncludesDocumentationForEveryOfficialProtocol(t *testing.T) {
if err != nil {
t.Fatal(err)
}
bundledCount := len(bundledWorkflowPluginManifests()) + len(bundledPaymentPluginManifests())
bundledCount := len(bundledWorkflowPluginManifests())
packageIDs := make(map[string]bool, len(packages))
for _, packagePath := range packages {
data, err := os.ReadFile(packagePath)
if err != nil {
t.Fatal(err)
}
pkg, err := protocol.ParsePluginPackage(data)
if err != nil {
t.Fatal(err)
}
packageIDs[pkg.Manifest.Metadata.ID] = true
}
for _, manifest := range bundledPaymentPluginManifests() {
if !packageIDs[manifest.Metadata.ID] {
bundledCount++
}
}
if len(plugins) != len(packages)+bundledCount {
t.Fatalf("plugin views = %d, official packages plus bundled plugins = %d", len(plugins), len(packages)+bundledCount)
}
@@ -47,8 +64,12 @@ func TestPluginViewIncludesDocumentationForEveryOfficialProtocol(t *testing.T) {
t.Errorf("fresh runtime did not install official plugin %q", pkg.Manifest.Metadata.ID)
continue
}
if plugin.Source != PluginOriginOfficial {
t.Errorf("plugin %q source = %q, want official", plugin.Manifest.ID, plugin.Source)
expectedSource := PluginOriginOfficial
if isSystemPaymentPluginID(plugin.Manifest.ID) {
expectedSource = PluginOriginSystem
}
if plugin.Source != expectedSource {
t.Errorf("plugin %q source = %q, want %s", plugin.Manifest.ID, plugin.Source, expectedSource)
}
expected := strings.TrimSpace(string(pkg.Files["README.md"])) + "\n\n---\n\n" + strings.TrimSpace(string(pkg.Files["docs/interface.md"]))
if strings.TrimSpace(plugin.Manifest.Documentation) != expected {
+7 -1
View File
@@ -110,7 +110,13 @@ func New(repo *repository.Repository, dataDir string) *Service {
func NewWithRuntimeCapabilities(repo *repository.Repository, dataDir string, capabilities RuntimeCapabilities) *Service {
coordinator, err := newRuntimeCoordinator(repo.Dialect())
pluginRuntime, pluginRuntimeErr := newPluginRuntime(dataDir)
service := &Service{repo: repo, dataDir: dataDir, runtimeCapabilities: capabilities, activeStorageTests: make(map[string]bool), activeCancels: make(map[string]context.CancelFunc), coordinator: coordinator, runtimeErr: err, pluginRuntime: pluginRuntime, pluginRuntimeErr: pluginRuntimeErr, paymentRegistry: payment.Builtins(), workerID: newID(), routeCatalogTTL: 30 * time.Second, routeCatalogMaxStale: 5 * time.Minute, routeHealthBlocked: make(map[string]time.Time)}
paymentRegistry, _ := payment.NewRegistry()
if pluginRuntime != nil {
if dynamic := pluginRuntime.paymentRegistrySnapshot(); dynamic != nil {
paymentRegistry = dynamic
}
}
service := &Service{repo: repo, dataDir: dataDir, runtimeCapabilities: capabilities, activeStorageTests: make(map[string]bool), activeCancels: make(map[string]context.CancelFunc), coordinator: coordinator, runtimeErr: err, pluginRuntime: pluginRuntime, pluginRuntimeErr: pluginRuntimeErr, paymentRegistry: paymentRegistry, workerID: newID(), routeCatalogTTL: 30 * time.Second, routeCatalogMaxStale: 5 * time.Minute, routeHealthBlocked: make(map[string]time.Time)}
service.taskBillingCoordinator = newTaskBillingCoordinator(service.repo)
service.taskTerminalCoordinator = newTaskTerminalCoordinator(service)
service.taskRouteExecutor = newTaskRouteExecutor(service)