用 Go 编写 AF (Application Function) 与 NEF 对接实现 QoS 动态切片
解读
在国内运营商 5G 专网、MEC 边缘云项目中,AF 作为第三方应用功能实体,需通过 NEF(Network Exposure Function) 调用核心网开放接口,对指定 PDU Session 进行 QoS 动态切片(即按需创建/修改/释放 QoS Flow)。面试时,考官想确认候选人是否真正理解:
- 3GPP TS 29.522 定义的 Nnef_AFsessionWithQoS 服务化接口;
- 如何基于 Go 的 net/http 快速实现 RESTful 客户端,完成 OAuth2 客户端凭证授权;
- 如何利用 go-jsoniter 或 protojson 高效序列化 3GPP 复杂嵌套结构;
- 如何用 goroutine + context 实现并发请求、超时熔断、重试退避;
- 如何设计 表驱动的单元测试,覆盖 201/204/400/401/403/404/500/503 全量返回码;
- 如何在 eBPF + kprobe 侧验证 QoS Flow 真正下发到 UPF,形成端到端闭环。
知识点
- 3GPP Nnef 接口资源模型:afTransactionId、qosReference、qosProfile、altQoSProfile、usageThreshold、timeWindow;
- HTTP/2 强制要求:NEF 仅暴露 HTTP/2,Go 需配置 http2.Transport 并开启 TLS1.3;
- OAuth2 客户端凭证流:向 AUSF 获取 access_token,scope 固定为 "nef-qos",token 有效期 3600 s,需 提前 30 s 刷新;
- QoS 动态切片生命周期:CREATE → MODIFY → DELETE,对应 POST /nnef-af-session/v1/{afTransactionId}/qos → PATCH → DELETE;
- 并发安全:同一 afTransactionId 可能被 5G 核心网异步回调,需用 sync.Map 存储本地会话元数据;
- 错误重试策略:对 429/500/503 采用 指数退避 + 全抖动,最大 5 次,退避基数 200 ms;
- 可观测性:使用 uber-go/zap 打印结构化日志,prometheus/client_golang 暴露 nef_request_total、nef_request_duration_seconds 两个 RED 指标;
- 单元测试:用 httptest.NewServer 伪造 NEF,结合 testify/mock 断言请求体字段;用 goleak 检测 goroutine 泄漏;
- 性能压测:用 vegeta 以 1000 RPS 持续 60 s,P99 延迟 < 120 ms,内存占用 < 200 MB;
- 安全合规:国密 SM2/SM3 双证书双向 TLS,国密 SSL 在 Go 1.20 通过 tls.Config.CipherSuites 显式开启。
答案
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"golang.org/x/net/http2"
)
const (
nefBase = "https://nef.5gc.mnc001.mcc460.3gppnetwork.org:443"
tokenURL = "https://ausf.5gc.mnc001.mcc460.3gppnetwork.org:443/oauth2/token"
clientID = "af001"
clientSecret = "af001-secret"
scope = "nef-qos"
)
var (
requestCounter = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "nef_request_total",
Help: "Total NEF requests",
}, []string{"method", "code"})
requestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "nef_request_duration_seconds",
Help: "Duration of NEF requests",
}, []string{"method"})
)
func init() {
prometheus.MustRegister(requestCounter, requestDuration)
}
type QoSProfile struct {
QosReference string `json:"qosReference"`
GBR *uint64 `json:"gbrUl,omitempty"`
MBR *uint64 `json:"mbrUl,omitempty"`
Priority uint8 `json:"priorityLevel"`
}
type QoSRequest struct {
QosProfile QoSProfile `json:"qosProfile"`
Supi string `json:"supi"`
PDUSessionID uint8 `json:"pduSessionId"`
DNN string `json:"dnn"`
SNSSAI string `json:"sNssai"`
}
type Client struct {
hc *http.Client
logger *zap.Logger
token string
tokenExpiry time.Time
mu sync.Mutex
}
func NewClient(logger *zap.Logger) *Client {
t2 := &http2.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS13,
CipherSuites: []uint16{tls.TLS_ECDHE_SM4_GCM_SM3}, // 国密示例
},
}
return &Client{
hc: &http.Client{Transport: t2, Timeout: 3 * time.Second},
logger: logger,
}
}
func (c *Client) getToken(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
if time.Now().Add(30 * time.Second).Before(c.tokenExpiry) {
return nil
}
form := url.Values{}
form.Set("grant_type", "client_credentials")
form.Set("client_id", clientID)
form.Set("client_secret", clientSecret)
form.Set("scope", scope)
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := c.hc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("token endpoint %d: %s", resp.StatusCode, body)
}
var tr struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
if err := json.NewDecoder(resp.Body).Decode(&tr); err != nil {
return err
}
c.token = tr.AccessToken
c.tokenExpiry = time.Now().Add(time.Duration(tr.ExpiresIn) * time.Second)
return nil
}
func (c *Client) do(ctx context.Context, method, path string, body interface{}) (*http.Response, error) {
if err := c.getToken(ctx); err != nil {
return nil, err
}
var buf io.Reader
if body != nil {
b, _ := json.Marshal(body)
buf = bytes.NewReader(b)
}
req, _ := http.NewRequestWithContext(ctx, method, nefBase+path, buf)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.token)
start := time.Now()
resp, err := c.hc.Do(req)
dur := time.Since(start).Seconds()
requestDuration.WithLabelValues(method).Observe(dur)
code := "0"
if resp != nil {
code = fmt.Sprintf("%d", resp.StatusCode)
}
requestCounter.WithLabelValues(method, code).Inc()
return resp, err
}
func (c *Client) CreateQoSFlow(ctx context.Context, afTransID string, req QoSRequest) error {
path := fmt.Sprintf("/nnef-af-session/v1/%s/qos", afTransID)
resp, err := c.do(ctx, http.MethodPost, path, req)
if err != nil {
return err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusCreated:
return nil
case http.StatusConflict:
return errors.New("qos flow already exists")
default:
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("unexpected status %d: %s", resp.StatusCode, body)
}
}
func (c *Client) DeleteQoSFlow(ctx context.Context, afTransID string) error {
path := fmt.Sprintf("/nnef-af-session/v1/%s/qos", afTransID)
resp, err := c.do(ctx, http.MethodDelete, path, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("unexpected status %d: %s", resp.StatusCode, body)
}
return nil
}
func main() {
logger, _ := zap.NewProduction()
cli := NewClient(logger)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req := QoSRequest{
QosProfile: QoSProfile{
QosReference: "QOS_1",
GBR: uint64Ptr(50 * 1024 * 1024), // 50 Mbps
MBR: uint64Ptr(100 * 1024 * 1024),
Priority: 5,
},
Supi: "imsi-460001234567890",
PDUSessionID: 5,
DNN: "internet.mnc001.mcc460.gprs",
SNSSAI: "1_001",
}
afTransID := "af-trans-123456"
if err := cli.CreateQoSFlow(ctx, afTransID, req); err != nil {
logger.Fatal("create qos flow failed", zap.Error(err))
}
logger.Info("qos flow created")
time.Sleep(30 * time.Second)
if err := cli.DeleteQoSFlow(ctx, afTransID); err != nil {
logger.Fatal("delete qos flow failed", zap.Error(err))
}
logger.Info("qos flow deleted")
}
func uint64Ptr(v uint64) *uint64 { return &v }
拓展思考
- 切片级联场景:若 AF 需对同一 SUPI 的多个 PDU Session 批量切片,可封装 errgroup.Group 并发调用,设置 context.WithTimeout 统一超时,失败时通过 compensate transaction 回滚已创建 Flow,保证 all-or-nothing;
- 事件回调可靠性:NEF 会通过 POST /af-callback/{afTransactionId}/qos-notify 推送资源释放事件,AF 需实现 幂等回调处理器,用 Redis SETNX 防止重复处理;
- 多厂家 NEF 适配:国内存在 华为、中兴、爱立信 三套 NEF,字段命名差异大(如 qosReference 在华为叫 "qosId"),可引入 go-mapstructure + yaml 配置 做字段映射,实现 插件化驱动;
- 性能极限优化:当 RPS > 5000 时,net/http 的 HPACK 动态表可能成为瓶颈,可替换为 fasthttp,但需自行实现 HTTP/2 与 OAuth2,权衡 内存零拷贝 与 协议完整性;
- 政策合规:工信部 5G 定制网 《QoS 切片计费规范》 要求 AF 上报 实际使用流量 与 切片模板 ID,需在 DeleteQoSFlow 前调用 NEF 计费确认接口,否则运营商会 拒绝话单 导致收入损失。