channel_service_test.go 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663
  1. //go:build unit
  2. package service
  3. import (
  4. "context"
  5. "errors"
  6. "net/http"
  7. "sync"
  8. "testing"
  9. infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
  10. "github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
  11. "github.com/stretchr/testify/require"
  12. "github.com/tidwall/gjson"
  13. )
  14. // ---------------------------------------------------------------------------
  15. // Mock: ChannelRepository
  16. // ---------------------------------------------------------------------------
  17. type mockChannelRepository struct {
  18. listAllFn func(ctx context.Context) ([]Channel, error)
  19. getGroupPlatformsFn func(ctx context.Context, groupIDs []int64) (map[int64]string, error)
  20. createFn func(ctx context.Context, channel *Channel) error
  21. getByIDFn func(ctx context.Context, id int64) (*Channel, error)
  22. updateFn func(ctx context.Context, channel *Channel) error
  23. deleteFn func(ctx context.Context, id int64) error
  24. listFn func(ctx context.Context, params pagination.PaginationParams, status, search string) ([]Channel, *pagination.PaginationResult, error)
  25. existsByNameFn func(ctx context.Context, name string) (bool, error)
  26. existsByNameExcludingFn func(ctx context.Context, name string, excludeID int64) (bool, error)
  27. getGroupIDsFn func(ctx context.Context, channelID int64) ([]int64, error)
  28. setGroupIDsFn func(ctx context.Context, channelID int64, groupIDs []int64) error
  29. getChannelIDByGroupIDFn func(ctx context.Context, groupID int64) (int64, error)
  30. getGroupsInOtherChannelsFn func(ctx context.Context, channelID int64, groupIDs []int64) ([]int64, error)
  31. listModelPricingFn func(ctx context.Context, channelID int64) ([]ChannelModelPricing, error)
  32. createModelPricingFn func(ctx context.Context, pricing *ChannelModelPricing) error
  33. updateModelPricingFn func(ctx context.Context, pricing *ChannelModelPricing) error
  34. deleteModelPricingFn func(ctx context.Context, id int64) error
  35. replaceModelPricingFn func(ctx context.Context, channelID int64, pricingList []ChannelModelPricing) error
  36. }
  37. func (m *mockChannelRepository) Create(ctx context.Context, channel *Channel) error {
  38. if m.createFn != nil {
  39. return m.createFn(ctx, channel)
  40. }
  41. return nil
  42. }
  43. func (m *mockChannelRepository) GetByID(ctx context.Context, id int64) (*Channel, error) {
  44. if m.getByIDFn != nil {
  45. return m.getByIDFn(ctx, id)
  46. }
  47. return nil, ErrChannelNotFound
  48. }
  49. func (m *mockChannelRepository) Update(ctx context.Context, channel *Channel) error {
  50. if m.updateFn != nil {
  51. return m.updateFn(ctx, channel)
  52. }
  53. return nil
  54. }
  55. func (m *mockChannelRepository) Delete(ctx context.Context, id int64) error {
  56. if m.deleteFn != nil {
  57. return m.deleteFn(ctx, id)
  58. }
  59. return nil
  60. }
  61. func (m *mockChannelRepository) List(ctx context.Context, params pagination.PaginationParams, status, search string) ([]Channel, *pagination.PaginationResult, error) {
  62. if m.listFn != nil {
  63. return m.listFn(ctx, params, status, search)
  64. }
  65. return nil, nil, nil
  66. }
  67. func (m *mockChannelRepository) ListAll(ctx context.Context) ([]Channel, error) {
  68. if m.listAllFn != nil {
  69. return m.listAllFn(ctx)
  70. }
  71. return nil, nil
  72. }
  73. func (m *mockChannelRepository) ExistsByName(ctx context.Context, name string) (bool, error) {
  74. if m.existsByNameFn != nil {
  75. return m.existsByNameFn(ctx, name)
  76. }
  77. return false, nil
  78. }
  79. func (m *mockChannelRepository) ExistsByNameExcluding(ctx context.Context, name string, excludeID int64) (bool, error) {
  80. if m.existsByNameExcludingFn != nil {
  81. return m.existsByNameExcludingFn(ctx, name, excludeID)
  82. }
  83. return false, nil
  84. }
  85. func (m *mockChannelRepository) GetGroupIDs(ctx context.Context, channelID int64) ([]int64, error) {
  86. if m.getGroupIDsFn != nil {
  87. return m.getGroupIDsFn(ctx, channelID)
  88. }
  89. return nil, nil
  90. }
  91. func (m *mockChannelRepository) SetGroupIDs(ctx context.Context, channelID int64, groupIDs []int64) error {
  92. if m.setGroupIDsFn != nil {
  93. return m.setGroupIDsFn(ctx, channelID, groupIDs)
  94. }
  95. return nil
  96. }
  97. func (m *mockChannelRepository) GetChannelIDByGroupID(ctx context.Context, groupID int64) (int64, error) {
  98. if m.getChannelIDByGroupIDFn != nil {
  99. return m.getChannelIDByGroupIDFn(ctx, groupID)
  100. }
  101. return 0, nil
  102. }
  103. func (m *mockChannelRepository) GetGroupsInOtherChannels(ctx context.Context, channelID int64, groupIDs []int64) ([]int64, error) {
  104. if m.getGroupsInOtherChannelsFn != nil {
  105. return m.getGroupsInOtherChannelsFn(ctx, channelID, groupIDs)
  106. }
  107. return nil, nil
  108. }
  109. func (m *mockChannelRepository) GetGroupPlatforms(ctx context.Context, groupIDs []int64) (map[int64]string, error) {
  110. if m.getGroupPlatformsFn != nil {
  111. return m.getGroupPlatformsFn(ctx, groupIDs)
  112. }
  113. return nil, nil
  114. }
  115. func (m *mockChannelRepository) ListModelPricing(ctx context.Context, channelID int64) ([]ChannelModelPricing, error) {
  116. if m.listModelPricingFn != nil {
  117. return m.listModelPricingFn(ctx, channelID)
  118. }
  119. return nil, nil
  120. }
  121. func (m *mockChannelRepository) CreateModelPricing(ctx context.Context, pricing *ChannelModelPricing) error {
  122. if m.createModelPricingFn != nil {
  123. return m.createModelPricingFn(ctx, pricing)
  124. }
  125. return nil
  126. }
  127. func (m *mockChannelRepository) UpdateModelPricing(ctx context.Context, pricing *ChannelModelPricing) error {
  128. if m.updateModelPricingFn != nil {
  129. return m.updateModelPricingFn(ctx, pricing)
  130. }
  131. return nil
  132. }
  133. func (m *mockChannelRepository) DeleteModelPricing(ctx context.Context, id int64) error {
  134. if m.deleteModelPricingFn != nil {
  135. return m.deleteModelPricingFn(ctx, id)
  136. }
  137. return nil
  138. }
  139. func (m *mockChannelRepository) ReplaceModelPricing(ctx context.Context, channelID int64, pricingList []ChannelModelPricing) error {
  140. if m.replaceModelPricingFn != nil {
  141. return m.replaceModelPricingFn(ctx, channelID, pricingList)
  142. }
  143. return nil
  144. }
  145. // ---------------------------------------------------------------------------
  146. // Mock: APIKeyAuthCacheInvalidator
  147. // ---------------------------------------------------------------------------
  148. type mockChannelAuthCacheInvalidator struct {
  149. invalidatedGroupIDs []int64
  150. invalidatedKeys []string
  151. invalidatedUserIDs []int64
  152. }
  153. type mockChannelCachePubSub struct {
  154. mu sync.Mutex
  155. handlers []func()
  156. }
  157. func (m *mockChannelCachePubSub) NotifyUpdate(context.Context) error {
  158. m.mu.Lock()
  159. handlers := append([]func(){}, m.handlers...)
  160. m.mu.Unlock()
  161. for _, handler := range handlers {
  162. handler()
  163. }
  164. return nil
  165. }
  166. func (m *mockChannelCachePubSub) SubscribeUpdates(_ context.Context, handler func()) {
  167. m.mu.Lock()
  168. m.handlers = append(m.handlers, handler)
  169. m.mu.Unlock()
  170. }
  171. func (m *mockChannelAuthCacheInvalidator) InvalidateAuthCacheByKey(_ context.Context, key string) {
  172. m.invalidatedKeys = append(m.invalidatedKeys, key)
  173. }
  174. func (m *mockChannelAuthCacheInvalidator) InvalidateAuthCacheByUserID(_ context.Context, userID int64) {
  175. m.invalidatedUserIDs = append(m.invalidatedUserIDs, userID)
  176. }
  177. func (m *mockChannelAuthCacheInvalidator) InvalidateAuthCacheByGroupID(_ context.Context, groupID int64) {
  178. m.invalidatedGroupIDs = append(m.invalidatedGroupIDs, groupID)
  179. }
  180. // ---------------------------------------------------------------------------
  181. // Helpers
  182. // ---------------------------------------------------------------------------
  183. func newTestChannelService(repo *mockChannelRepository) *ChannelService {
  184. return NewChannelService(repo, nil, nil, nil, nil)
  185. }
  186. func newTestChannelServiceWithAuth(repo *mockChannelRepository, auth *mockChannelAuthCacheInvalidator) *ChannelService {
  187. return NewChannelService(repo, nil, auth, nil, nil)
  188. }
  189. // makeStandardRepo returns a repo that serves one active channel with anthropic pricing
  190. // for group 1, with the given model pricing and model mapping.
  191. func makeStandardRepo(ch Channel, groupPlatforms map[int64]string) *mockChannelRepository {
  192. return &mockChannelRepository{
  193. listAllFn: func(_ context.Context) ([]Channel, error) {
  194. return []Channel{ch}, nil
  195. },
  196. getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
  197. return groupPlatforms, nil
  198. },
  199. }
  200. }
  201. // ===========================================================================
  202. // 1. BuildModelMappingChain
  203. // ===========================================================================
  204. func TestBuildModelMappingChain(t *testing.T) {
  205. tests := []struct {
  206. name string
  207. result ChannelMappingResult
  208. requestModel string
  209. upstreamModel string
  210. want string
  211. }{
  212. {
  213. name: "no mapping, no upstream diff",
  214. result: ChannelMappingResult{Mapped: false, MappedModel: "claude-sonnet-4"},
  215. requestModel: "claude-sonnet-4",
  216. upstreamModel: "claude-sonnet-4",
  217. want: "",
  218. },
  219. {
  220. name: "no mapping, upstream differs",
  221. result: ChannelMappingResult{Mapped: false, MappedModel: "claude-sonnet-4"},
  222. requestModel: "claude-sonnet-4",
  223. upstreamModel: "claude-sonnet-4-20250514",
  224. want: "claude-sonnet-4\u2192claude-sonnet-4-20250514",
  225. },
  226. {
  227. name: "mapped, upstream differs",
  228. result: ChannelMappingResult{Mapped: true, MappedModel: "claude-sonnet-4-20250514"},
  229. requestModel: "my-model",
  230. upstreamModel: "actual-upstream",
  231. want: "my-model\u2192claude-sonnet-4-20250514\u2192actual-upstream",
  232. },
  233. {
  234. name: "mapped, upstream same as mapped",
  235. result: ChannelMappingResult{Mapped: true, MappedModel: "claude-sonnet-4-20250514"},
  236. requestModel: "claude-sonnet-4",
  237. upstreamModel: "claude-sonnet-4-20250514",
  238. want: "claude-sonnet-4\u2192claude-sonnet-4-20250514",
  239. },
  240. {
  241. name: "mapped, upstream empty",
  242. result: ChannelMappingResult{Mapped: true, MappedModel: "target-model"},
  243. requestModel: "my-model",
  244. upstreamModel: "",
  245. want: "my-model\u2192target-model",
  246. },
  247. }
  248. for _, tt := range tests {
  249. t.Run(tt.name, func(t *testing.T) {
  250. got := tt.result.BuildModelMappingChain(tt.requestModel, tt.upstreamModel)
  251. require.Equal(t, tt.want, got)
  252. })
  253. }
  254. }
  255. // ===========================================================================
  256. // 2. ReplaceModelInBody
  257. // ===========================================================================
  258. func TestReplaceModelInBody(t *testing.T) {
  259. tests := []struct {
  260. name string
  261. body []byte
  262. newModel string
  263. check func(t *testing.T, result []byte)
  264. }{
  265. {
  266. name: "empty body",
  267. body: []byte{},
  268. newModel: "new-model",
  269. check: func(t *testing.T, result []byte) {
  270. require.Equal(t, []byte{}, result)
  271. },
  272. },
  273. {
  274. name: "model already equal",
  275. body: []byte(`{"model":"claude-sonnet-4","temperature":0.7}`),
  276. newModel: "claude-sonnet-4",
  277. check: func(t *testing.T, result []byte) {
  278. require.Equal(t, []byte(`{"model":"claude-sonnet-4","temperature":0.7}`), result)
  279. },
  280. },
  281. {
  282. name: "model different",
  283. body: []byte(`{"model":"claude-sonnet-4","temperature":0.7}`),
  284. newModel: "claude-opus-4",
  285. check: func(t *testing.T, result []byte) {
  286. require.Contains(t, string(result), `"model":"claude-opus-4"`)
  287. require.Contains(t, string(result), `"temperature"`)
  288. },
  289. },
  290. {
  291. name: "no model field",
  292. body: []byte(`{"temperature":0.7}`),
  293. newModel: "claude-opus-4",
  294. check: func(t *testing.T, result []byte) {
  295. require.Contains(t, string(result), `"model":"claude-opus-4"`)
  296. require.Contains(t, string(result), `"temperature"`)
  297. },
  298. },
  299. }
  300. for _, tt := range tests {
  301. t.Run(tt.name, func(t *testing.T) {
  302. result := ReplaceModelInBody(tt.body, tt.newModel)
  303. tt.check(t, result)
  304. })
  305. }
  306. }
  307. // ===========================================================================
  308. // 3. validateNoConflictingModels + validateNoConflictingMappings
  309. // ===========================================================================
  310. func TestValidateNoConflictingModels(t *testing.T) {
  311. tests := []struct {
  312. name string
  313. pricingList []ChannelModelPricing
  314. wantErr bool
  315. errContains string
  316. }{
  317. {
  318. name: "no duplicates",
  319. pricingList: []ChannelModelPricing{
  320. {Platform: "anthropic", Models: []string{"claude-sonnet-4", "claude-opus-4"}},
  321. {Platform: "openai", Models: []string{"gpt-5.1"}},
  322. },
  323. wantErr: false,
  324. },
  325. {
  326. name: "same platform duplicate",
  327. pricingList: []ChannelModelPricing{
  328. {Platform: "anthropic", Models: []string{"claude-sonnet-4"}},
  329. {Platform: "anthropic", Models: []string{"claude-sonnet-4"}},
  330. },
  331. wantErr: true,
  332. errContains: "claude-sonnet-4",
  333. },
  334. {
  335. name: "same model different platform",
  336. pricingList: []ChannelModelPricing{
  337. {Platform: "anthropic", Models: []string{"model-a"}},
  338. {Platform: "openai", Models: []string{"model-a"}},
  339. },
  340. wantErr: false,
  341. },
  342. {
  343. name: "case insensitive",
  344. pricingList: []ChannelModelPricing{
  345. {Platform: "anthropic", Models: []string{"Claude"}},
  346. {Platform: "anthropic", Models: []string{"claude"}},
  347. },
  348. wantErr: true,
  349. },
  350. {
  351. name: "empty list (nil)",
  352. pricingList: nil,
  353. wantErr: false,
  354. },
  355. {
  356. name: "wildcard_vs_wildcard_conflict",
  357. pricingList: []ChannelModelPricing{
  358. {Platform: "anthropic", Models: []string{"claude-*"}},
  359. {Platform: "anthropic", Models: []string{"claude-opus-*"}},
  360. },
  361. wantErr: true,
  362. errContains: "conflict",
  363. },
  364. {
  365. name: "wildcard_vs_exact_conflict",
  366. pricingList: []ChannelModelPricing{
  367. {Platform: "anthropic", Models: []string{"claude-*"}},
  368. {Platform: "anthropic", Models: []string{"claude-opus-4-6"}},
  369. },
  370. wantErr: true,
  371. errContains: "conflict",
  372. },
  373. {
  374. name: "no_conflict_different_platform",
  375. pricingList: []ChannelModelPricing{
  376. {Platform: "anthropic", Models: []string{"claude-opus-*"}},
  377. {Platform: "openai", Models: []string{"claude-*"}},
  378. },
  379. wantErr: false,
  380. },
  381. {
  382. name: "no_conflict_same_platform_different_prefix",
  383. pricingList: []ChannelModelPricing{
  384. {Platform: "anthropic", Models: []string{"claude-opus-*"}},
  385. {Platform: "anthropic", Models: []string{"gpt-*"}},
  386. },
  387. wantErr: false,
  388. },
  389. {
  390. name: "catch_all_wildcard_conflicts_with_everything",
  391. pricingList: []ChannelModelPricing{
  392. {Platform: "openai", Models: []string{"*"}},
  393. {Platform: "openai", Models: []string{"gpt-5"}},
  394. },
  395. wantErr: true,
  396. errContains: "conflict",
  397. },
  398. // 以下三例:冲突检测必须与 normalizeChannelPricingModelName 用同一套归一化,
  399. // 否则校验放行、写进缓存后键相同,后写的定价会静默覆盖前一条。
  400. {
  401. name: "claude_dot_and_hyphen_spelling_conflict",
  402. pricingList: []ChannelModelPricing{
  403. {Platform: "anthropic", Models: []string{"claude-sonnet-4.5"}},
  404. {Platform: "anthropic", Models: []string{"claude-sonnet-4-5"}},
  405. },
  406. wantErr: true,
  407. errContains: "conflict",
  408. },
  409. {
  410. name: "claude_dot_and_hyphen_spelling_conflict_wildcard",
  411. pricingList: []ChannelModelPricing{
  412. {Platform: "anthropic", Models: []string{"claude-sonnet-4.5*"}},
  413. {Platform: "anthropic", Models: []string{"claude-sonnet-4-5-x"}},
  414. },
  415. wantErr: true,
  416. errContains: "conflict",
  417. },
  418. {
  419. name: "surrounding_whitespace_conflict",
  420. pricingList: []ChannelModelPricing{
  421. {Platform: "openai", Models: []string{"gpt-5.6"}},
  422. {Platform: "openai", Models: []string{" gpt-5.6 "}},
  423. },
  424. wantErr: true,
  425. errContains: "conflict",
  426. },
  427. {
  428. // 只有 claude-* 前缀才做 "." → "-",别把其它平台也一起归一化了
  429. name: "non_claude_dot_spelling_is_not_normalized",
  430. pricingList: []ChannelModelPricing{
  431. {Platform: "openai", Models: []string{"gpt-5.6"}},
  432. {Platform: "openai", Models: []string{"gpt-5-6"}},
  433. },
  434. wantErr: false,
  435. },
  436. }
  437. for _, tt := range tests {
  438. t.Run(tt.name, func(t *testing.T) {
  439. err := validateNoConflictingModels(tt.pricingList)
  440. if tt.wantErr {
  441. require.Error(t, err)
  442. if tt.errContains != "" {
  443. require.Contains(t, err.Error(), tt.errContains)
  444. }
  445. } else {
  446. require.NoError(t, err)
  447. }
  448. })
  449. }
  450. // Additional sub-case: explicit empty slice
  451. t.Run("empty list (empty slice)", func(t *testing.T) {
  452. err := validateNoConflictingModels([]ChannelModelPricing{})
  453. require.NoError(t, err)
  454. })
  455. }
  456. func TestValidateNoConflictingMappings(t *testing.T) {
  457. tests := []struct {
  458. name string
  459. mapping map[string]map[string]string
  460. wantErr bool
  461. errContains string
  462. }{
  463. {
  464. name: "nil mapping",
  465. mapping: nil,
  466. wantErr: false,
  467. },
  468. {
  469. name: "empty mapping",
  470. mapping: map[string]map[string]string{},
  471. wantErr: false,
  472. },
  473. {
  474. name: "no conflict",
  475. mapping: map[string]map[string]string{
  476. "anthropic": {"claude-opus-*": "opus", "gpt-*": "gpt"},
  477. },
  478. wantErr: false,
  479. },
  480. {
  481. name: "wildcard vs wildcard conflict",
  482. mapping: map[string]map[string]string{
  483. "anthropic": {"claude-*": "a", "claude-opus-*": "b"},
  484. },
  485. wantErr: true,
  486. errContains: "conflict",
  487. },
  488. {
  489. // 映射缓存(expandMappingToCache)只做 strings.ToLower,不做定价那套
  490. // "." → "-",所以这两个源模式在缓存里是两个不同的键、并不冲突。
  491. // 这条用来卡住:定价侧的归一化修复不能顺手套到映射侧,否则会误报冲突。
  492. name: "mapping keeps dot and hyphen spelling separate",
  493. mapping: map[string]map[string]string{
  494. "anthropic": {"claude-sonnet-4.5": "a", "claude-sonnet-4-5": "b"},
  495. },
  496. wantErr: false,
  497. },
  498. {
  499. name: "wildcard vs exact conflict",
  500. mapping: map[string]map[string]string{
  501. "openai": {"gpt-*": "a", "gpt-4o": "b"},
  502. },
  503. wantErr: true,
  504. errContains: "conflict",
  505. },
  506. {
  507. name: "exact duplicate conflict",
  508. mapping: map[string]map[string]string{
  509. "anthropic": {"claude-opus-4": "a"},
  510. "openai": {"claude-opus-4": "b"},
  511. },
  512. wantErr: false, // different platforms
  513. },
  514. {
  515. name: "different platforms no conflict",
  516. mapping: map[string]map[string]string{
  517. "anthropic": {"claude-*": "a"},
  518. "openai": {"claude-*": "b"},
  519. },
  520. wantErr: false,
  521. },
  522. }
  523. for _, tt := range tests {
  524. t.Run(tt.name, func(t *testing.T) {
  525. err := validateNoConflictingMappings(tt.mapping)
  526. if tt.wantErr {
  527. require.Error(t, err)
  528. if tt.errContains != "" {
  529. require.Contains(t, err.Error(), tt.errContains)
  530. }
  531. } else {
  532. require.NoError(t, err)
  533. }
  534. })
  535. }
  536. }
  537. func TestConflictsBetween(t *testing.T) {
  538. tests := []struct {
  539. name string
  540. a, b modelEntry
  541. want bool
  542. }{
  543. {
  544. name: "exact same",
  545. a: modelEntry{prefix: "claude-opus-4", wildcard: false},
  546. b: modelEntry{prefix: "claude-opus-4", wildcard: false},
  547. want: true,
  548. },
  549. {
  550. name: "exact different",
  551. a: modelEntry{prefix: "claude-opus-4", wildcard: false},
  552. b: modelEntry{prefix: "gpt-4o", wildcard: false},
  553. want: false,
  554. },
  555. {
  556. name: "wildcard matches exact",
  557. a: modelEntry{prefix: "claude-", wildcard: true},
  558. b: modelEntry{prefix: "claude-opus-4", wildcard: false},
  559. want: true,
  560. },
  561. {
  562. name: "exact does not match unrelated wildcard",
  563. a: modelEntry{prefix: "gpt-4o", wildcard: false},
  564. b: modelEntry{prefix: "claude-", wildcard: true},
  565. want: false,
  566. },
  567. {
  568. name: "wildcard prefix overlap",
  569. a: modelEntry{prefix: "claude-", wildcard: true},
  570. b: modelEntry{prefix: "claude-opus-", wildcard: true},
  571. want: true,
  572. },
  573. {
  574. name: "wildcards no overlap",
  575. a: modelEntry{prefix: "claude-", wildcard: true},
  576. b: modelEntry{prefix: "gpt-", wildcard: true},
  577. want: false,
  578. },
  579. {
  580. name: "catch-all wildcard vs any",
  581. a: modelEntry{prefix: "", wildcard: true},
  582. b: modelEntry{prefix: "anything", wildcard: false},
  583. want: true,
  584. },
  585. }
  586. for _, tt := range tests {
  587. t.Run(tt.name, func(t *testing.T) {
  588. require.Equal(t, tt.want, conflictsBetween(tt.a, tt.b))
  589. })
  590. }
  591. }
  592. // ===========================================================================
  593. // 4. Cache Building + Hot Path Methods
  594. // ===========================================================================
  595. // --- 4.1 GetChannelForGroup ---
  596. func TestGetChannelForGroup_Success(t *testing.T) {
  597. ch := Channel{
  598. ID: 1,
  599. Name: "test-channel",
  600. Status: StatusActive,
  601. GroupIDs: []int64{10},
  602. }
  603. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  604. svc := newTestChannelService(repo)
  605. result, err := svc.GetChannelForGroup(context.Background(), 10)
  606. require.NoError(t, err)
  607. require.NotNil(t, result)
  608. require.Equal(t, int64(1), result.ID)
  609. require.Equal(t, "test-channel", result.Name)
  610. // returned value should be a clone
  611. result.Name = "mutated"
  612. result2, err := svc.GetChannelForGroup(context.Background(), 10)
  613. require.NoError(t, err)
  614. require.Equal(t, "test-channel", result2.Name)
  615. }
  616. func TestGetChannelForGroup_InactiveChannel(t *testing.T) {
  617. ch := Channel{
  618. ID: 1,
  619. Status: StatusDisabled,
  620. GroupIDs: []int64{10},
  621. }
  622. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  623. svc := newTestChannelService(repo)
  624. result, err := svc.GetChannelForGroup(context.Background(), 10)
  625. require.NoError(t, err)
  626. require.Nil(t, result)
  627. }
  628. func TestGetChannelForGroup_NoChannel(t *testing.T) {
  629. ch := Channel{
  630. ID: 1,
  631. Status: StatusActive,
  632. GroupIDs: []int64{10},
  633. }
  634. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  635. svc := newTestChannelService(repo)
  636. result, err := svc.GetChannelForGroup(context.Background(), 999)
  637. require.NoError(t, err)
  638. require.Nil(t, result)
  639. }
  640. func TestGetChannelForGroup_CacheError(t *testing.T) {
  641. repo := &mockChannelRepository{
  642. listAllFn: func(_ context.Context) ([]Channel, error) {
  643. return nil, errors.New("db connection failed")
  644. },
  645. }
  646. svc := newTestChannelService(repo)
  647. result, err := svc.GetChannelForGroup(context.Background(), 10)
  648. require.Error(t, err)
  649. require.Nil(t, result)
  650. require.Contains(t, err.Error(), "db connection failed")
  651. }
  652. // --- 4.2 GetChannelModelPricing ---
  653. func TestGetChannelModelPricing_ExactMatch(t *testing.T) {
  654. ch := Channel{
  655. ID: 1,
  656. Status: StatusActive,
  657. GroupIDs: []int64{10},
  658. ModelPricing: []ChannelModelPricing{
  659. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}, InputPrice: testPtrFloat64(15e-6)},
  660. },
  661. }
  662. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  663. svc := newTestChannelService(repo)
  664. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  665. require.NotNil(t, result)
  666. require.Equal(t, int64(100), result.ID)
  667. require.InDelta(t, 15e-6, *result.InputPrice, 1e-12)
  668. }
  669. func TestGetChannelModelPricing_CaseInsensitive(t *testing.T) {
  670. ch := Channel{
  671. ID: 1,
  672. Status: StatusActive,
  673. GroupIDs: []int64{10},
  674. ModelPricing: []ChannelModelPricing{
  675. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}, InputPrice: testPtrFloat64(15e-6)},
  676. },
  677. }
  678. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  679. svc := newTestChannelService(repo)
  680. result := svc.GetChannelModelPricing(context.Background(), 10, "Claude-Opus-4")
  681. require.NotNil(t, result)
  682. require.Equal(t, int64(100), result.ID)
  683. }
  684. func TestGetChannelModelPricing_NormalizesDotsAndHyphens(t *testing.T) {
  685. ch := Channel{
  686. ID: 1,
  687. Status: StatusActive,
  688. GroupIDs: []int64{10},
  689. ModelPricing: []ChannelModelPricing{
  690. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4.8"}, BillingMode: BillingModePerRequest, PerRequestPrice: testPtrFloat64(0.007)},
  691. },
  692. }
  693. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  694. svc := newTestChannelService(repo)
  695. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4-8")
  696. require.NotNil(t, result)
  697. require.Equal(t, int64(100), result.ID)
  698. require.Equal(t, BillingModePerRequest, result.BillingMode)
  699. require.InDelta(t, 0.007, *result.PerRequestPrice, 1e-12)
  700. }
  701. func TestGetChannelModelPricing_WildcardMatch(t *testing.T) {
  702. ch := Channel{
  703. ID: 1,
  704. Status: StatusActive,
  705. GroupIDs: []int64{10},
  706. ModelPricing: []ChannelModelPricing{
  707. {ID: 200, Platform: "anthropic", Models: []string{"claude-*"}, InputPrice: testPtrFloat64(10e-6)},
  708. },
  709. }
  710. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  711. svc := newTestChannelService(repo)
  712. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-sonnet-4")
  713. require.NotNil(t, result)
  714. require.Equal(t, int64(200), result.ID)
  715. }
  716. func TestGetChannelModelPricing_WildcardFirstMatch(t *testing.T) {
  717. ch := Channel{
  718. ID: 1,
  719. Status: StatusActive,
  720. GroupIDs: []int64{10},
  721. ModelPricing: []ChannelModelPricing{
  722. {ID: 200, Platform: "anthropic", Models: []string{"claude-*"}, InputPrice: testPtrFloat64(10e-6)},
  723. {ID: 300, Platform: "anthropic", Models: []string{"claude-sonnet-*"}, InputPrice: testPtrFloat64(5e-6)},
  724. },
  725. }
  726. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  727. svc := newTestChannelService(repo)
  728. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-sonnet-4-20250514")
  729. require.NotNil(t, result)
  730. // "claude-*" is defined first, so it matches first regardless of prefix length
  731. require.Equal(t, int64(200), result.ID)
  732. require.InDelta(t, 10e-6, *result.InputPrice, 1e-12)
  733. }
  734. func TestGetChannelModelPricing_NoMatch(t *testing.T) {
  735. ch := Channel{
  736. ID: 1,
  737. Status: StatusActive,
  738. GroupIDs: []int64{10},
  739. ModelPricing: []ChannelModelPricing{
  740. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}, InputPrice: testPtrFloat64(15e-6)},
  741. },
  742. }
  743. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  744. svc := newTestChannelService(repo)
  745. result := svc.GetChannelModelPricing(context.Background(), 10, "gpt-5.1")
  746. require.Nil(t, result)
  747. }
  748. func TestGetChannelModelPricing_InactiveChannel(t *testing.T) {
  749. ch := Channel{
  750. ID: 1,
  751. Status: StatusDisabled,
  752. GroupIDs: []int64{10},
  753. ModelPricing: []ChannelModelPricing{
  754. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}},
  755. },
  756. }
  757. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  758. svc := newTestChannelService(repo)
  759. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  760. require.Nil(t, result)
  761. }
  762. func TestGetChannelModelPricing_PlatformFiltering(t *testing.T) {
  763. ch := Channel{
  764. ID: 1,
  765. Status: StatusActive,
  766. GroupIDs: []int64{10, 20},
  767. ModelPricing: []ChannelModelPricing{
  768. {ID: 100, Platform: "openai", Models: []string{"gpt-5.1"}, InputPrice: testPtrFloat64(5e-6)},
  769. {ID: 200, Platform: "anthropic", Models: []string{"claude-opus-4"}, InputPrice: testPtrFloat64(15e-6)},
  770. },
  771. }
  772. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic", 20: "openai"})
  773. svc := newTestChannelService(repo)
  774. // Group 10 (anthropic) should NOT see openai pricing
  775. result := svc.GetChannelModelPricing(context.Background(), 10, "gpt-5.1")
  776. require.Nil(t, result)
  777. // Group 10 (anthropic) should see anthropic pricing
  778. result = svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  779. require.NotNil(t, result)
  780. require.Equal(t, int64(200), result.ID)
  781. // Group 20 (openai) should see openai pricing
  782. result = svc.GetChannelModelPricing(context.Background(), 20, "gpt-5.1")
  783. require.NotNil(t, result)
  784. require.Equal(t, int64(100), result.ID)
  785. // Group 20 (openai) should NOT see anthropic pricing
  786. result = svc.GetChannelModelPricing(context.Background(), 20, "claude-opus-4")
  787. require.Nil(t, result)
  788. }
  789. func TestGetChannelModelPricing_ReturnsCopy(t *testing.T) {
  790. ch := Channel{
  791. ID: 1,
  792. Status: StatusActive,
  793. GroupIDs: []int64{10},
  794. ModelPricing: []ChannelModelPricing{
  795. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}, InputPrice: testPtrFloat64(15e-6)},
  796. },
  797. }
  798. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  799. svc := newTestChannelService(repo)
  800. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  801. require.NotNil(t, result)
  802. // Mutate the returned pricing's slice fields — original cache should not be affected
  803. // (Clone copies slices independently, pointer fields are shared per design)
  804. result.Models = append(result.Models, "hacked")
  805. result.ID = 999
  806. // Original cache should not be affected (slice independence + struct copy)
  807. result2 := svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  808. require.NotNil(t, result2)
  809. require.Equal(t, 1, len(result2.Models))
  810. require.Equal(t, int64(100), result2.ID)
  811. }
  812. // --- 4.3 ResolveChannelMapping ---
  813. func TestResolveChannelMapping_NoChannel(t *testing.T) {
  814. ch := Channel{
  815. ID: 1,
  816. Status: StatusActive,
  817. GroupIDs: []int64{10},
  818. }
  819. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  820. svc := newTestChannelService(repo)
  821. // Group 999 is not in any channel
  822. result := svc.ResolveChannelMapping(context.Background(), 999, "claude-opus-4")
  823. require.Equal(t, "claude-opus-4", result.MappedModel)
  824. require.False(t, result.Mapped)
  825. require.Equal(t, int64(0), result.ChannelID)
  826. }
  827. func TestResolveChannelMapping_ExactMapping(t *testing.T) {
  828. ch := Channel{
  829. ID: 1,
  830. Status: StatusActive,
  831. GroupIDs: []int64{10},
  832. ModelMapping: map[string]map[string]string{
  833. "anthropic": {
  834. "claude-sonnet-4": "claude-sonnet-4-20250514",
  835. },
  836. },
  837. }
  838. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  839. svc := newTestChannelService(repo)
  840. result := svc.ResolveChannelMapping(context.Background(), 10, "claude-sonnet-4")
  841. require.True(t, result.Mapped)
  842. require.Equal(t, "claude-sonnet-4-20250514", result.MappedModel)
  843. require.Equal(t, int64(1), result.ChannelID)
  844. }
  845. func TestResolveChannelMapping_WildcardMapping(t *testing.T) {
  846. ch := Channel{
  847. ID: 1,
  848. Status: StatusActive,
  849. GroupIDs: []int64{10},
  850. ModelMapping: map[string]map[string]string{
  851. "anthropic": {
  852. "*": "gpt-5.4",
  853. },
  854. },
  855. }
  856. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  857. svc := newTestChannelService(repo)
  858. result := svc.ResolveChannelMapping(context.Background(), 10, "any-model-name")
  859. require.True(t, result.Mapped)
  860. require.Equal(t, "gpt-5.4", result.MappedModel)
  861. }
  862. func TestResolveChannelMapping_WildcardFirstMatch(t *testing.T) {
  863. ch := Channel{
  864. ID: 1,
  865. Status: StatusActive,
  866. GroupIDs: []int64{10},
  867. ModelMapping: map[string]map[string]string{
  868. "anthropic": {
  869. "claude-*": "target2",
  870. "claude-sonnet-*": "target1",
  871. },
  872. },
  873. }
  874. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  875. svc := newTestChannelService(repo)
  876. result := svc.ResolveChannelMapping(context.Background(), 10, "claude-sonnet-4")
  877. require.True(t, result.Mapped)
  878. // map iteration order is non-deterministic, so the first-match depends on
  879. // insertion order which Go maps don't guarantee; verify that one of the
  880. // wildcard targets matched
  881. require.Contains(t, []string{"target1", "target2"}, result.MappedModel)
  882. }
  883. func TestResolveChannelMapping_NoMapping(t *testing.T) {
  884. ch := Channel{
  885. ID: 1,
  886. Status: StatusActive,
  887. GroupIDs: []int64{10},
  888. ModelMapping: map[string]map[string]string{
  889. "anthropic": {
  890. "claude-sonnet-4": "mapped",
  891. },
  892. },
  893. }
  894. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  895. svc := newTestChannelService(repo)
  896. result := svc.ResolveChannelMapping(context.Background(), 10, "claude-opus-4")
  897. require.False(t, result.Mapped)
  898. require.Equal(t, "claude-opus-4", result.MappedModel)
  899. require.Equal(t, int64(1), result.ChannelID)
  900. }
  901. func TestResolveChannelMapping_DefaultBillingModelSource(t *testing.T) {
  902. ch := Channel{
  903. ID: 1,
  904. Status: StatusActive,
  905. GroupIDs: []int64{10},
  906. BillingModelSource: "", // empty
  907. }
  908. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  909. svc := newTestChannelService(repo)
  910. result := svc.ResolveChannelMapping(context.Background(), 10, "claude-opus-4")
  911. require.Equal(t, BillingModelSourceChannelMapped, result.BillingModelSource)
  912. }
  913. func TestResolveChannelMapping_UpstreamBillingModelSource(t *testing.T) {
  914. ch := Channel{
  915. ID: 1,
  916. Status: StatusActive,
  917. GroupIDs: []int64{10},
  918. BillingModelSource: BillingModelSourceUpstream,
  919. }
  920. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  921. svc := newTestChannelService(repo)
  922. result := svc.ResolveChannelMapping(context.Background(), 10, "claude-opus-4")
  923. require.Equal(t, BillingModelSourceUpstream, result.BillingModelSource)
  924. }
  925. func TestResolveChannelMapping_InactiveChannel(t *testing.T) {
  926. ch := Channel{
  927. ID: 1,
  928. Status: StatusDisabled,
  929. GroupIDs: []int64{10},
  930. ModelMapping: map[string]map[string]string{
  931. "anthropic": {
  932. "claude-sonnet-4": "mapped",
  933. },
  934. },
  935. }
  936. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  937. svc := newTestChannelService(repo)
  938. result := svc.ResolveChannelMapping(context.Background(), 10, "claude-sonnet-4")
  939. require.False(t, result.Mapped)
  940. require.Equal(t, "claude-sonnet-4", result.MappedModel)
  941. require.Equal(t, int64(0), result.ChannelID) // no channel
  942. }
  943. // --- 4.4 IsModelRestricted ---
  944. func TestIsModelRestricted_NoChannel(t *testing.T) {
  945. ch := Channel{
  946. ID: 1,
  947. Status: StatusActive,
  948. GroupIDs: []int64{10},
  949. RestrictModels: true,
  950. }
  951. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  952. svc := newTestChannelService(repo)
  953. // Group 999 is not in any channel
  954. restricted := svc.IsModelRestricted(context.Background(), 999, "claude-opus-4")
  955. require.False(t, restricted)
  956. }
  957. func TestIsModelRestricted_RestrictDisabled(t *testing.T) {
  958. ch := Channel{
  959. ID: 1,
  960. Status: StatusActive,
  961. GroupIDs: []int64{10},
  962. RestrictModels: false,
  963. ModelPricing: []ChannelModelPricing{
  964. {Platform: "anthropic", Models: []string{"claude-opus-4"}},
  965. },
  966. }
  967. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  968. svc := newTestChannelService(repo)
  969. // Even though model is not in pricing, RestrictModels=false
  970. restricted := svc.IsModelRestricted(context.Background(), 10, "nonexistent-model")
  971. require.False(t, restricted)
  972. }
  973. func TestIsModelRestricted_InactiveChannel(t *testing.T) {
  974. ch := Channel{
  975. ID: 1,
  976. Status: StatusDisabled,
  977. GroupIDs: []int64{10},
  978. RestrictModels: true,
  979. }
  980. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  981. svc := newTestChannelService(repo)
  982. restricted := svc.IsModelRestricted(context.Background(), 10, "any-model")
  983. require.False(t, restricted)
  984. }
  985. func TestIsModelRestricted_ModelInPricing(t *testing.T) {
  986. ch := Channel{
  987. ID: 1,
  988. Status: StatusActive,
  989. GroupIDs: []int64{10},
  990. RestrictModels: true,
  991. ModelPricing: []ChannelModelPricing{
  992. {Platform: "anthropic", Models: []string{"claude-opus-4", "claude-sonnet-4"}},
  993. },
  994. }
  995. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  996. svc := newTestChannelService(repo)
  997. restricted := svc.IsModelRestricted(context.Background(), 10, "claude-opus-4")
  998. require.False(t, restricted)
  999. }
  1000. func TestIsModelRestricted_ModelInWildcard(t *testing.T) {
  1001. ch := Channel{
  1002. ID: 1,
  1003. Status: StatusActive,
  1004. GroupIDs: []int64{10},
  1005. RestrictModels: true,
  1006. ModelPricing: []ChannelModelPricing{
  1007. {Platform: "anthropic", Models: []string{"claude-*"}},
  1008. },
  1009. }
  1010. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  1011. svc := newTestChannelService(repo)
  1012. restricted := svc.IsModelRestricted(context.Background(), 10, "claude-sonnet-4")
  1013. require.False(t, restricted)
  1014. }
  1015. func TestIsModelRestricted_ModelNotFound(t *testing.T) {
  1016. ch := Channel{
  1017. ID: 1,
  1018. Status: StatusActive,
  1019. GroupIDs: []int64{10},
  1020. RestrictModels: true,
  1021. ModelPricing: []ChannelModelPricing{
  1022. {Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1023. },
  1024. }
  1025. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  1026. svc := newTestChannelService(repo)
  1027. restricted := svc.IsModelRestricted(context.Background(), 10, "gpt-5.1")
  1028. require.True(t, restricted)
  1029. }
  1030. func TestIsModelRestricted_CaseInsensitive(t *testing.T) {
  1031. ch := Channel{
  1032. ID: 1,
  1033. Status: StatusActive,
  1034. GroupIDs: []int64{10},
  1035. RestrictModels: true,
  1036. ModelPricing: []ChannelModelPricing{
  1037. {Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1038. },
  1039. }
  1040. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  1041. svc := newTestChannelService(repo)
  1042. restricted := svc.IsModelRestricted(context.Background(), 10, "Claude-Opus-4")
  1043. require.False(t, restricted)
  1044. }
  1045. // --- 4.5 ResolveChannelMappingAndRestrict ---
  1046. // 注意:模型限制检查已移至调度阶段(GatewayService.checkChannelPricingRestriction),
  1047. // ResolveChannelMappingAndRestrict 仅做映射,restricted 始终为 false。
  1048. func TestResolveChannelMappingAndRestrict_NilGroupID(t *testing.T) {
  1049. repo := &mockChannelRepository{
  1050. listAllFn: func(_ context.Context) ([]Channel, error) {
  1051. return nil, nil
  1052. },
  1053. }
  1054. svc := newTestChannelService(repo)
  1055. mapping, restricted := svc.ResolveChannelMappingAndRestrict(context.Background(), nil, "claude-opus-4")
  1056. require.False(t, restricted)
  1057. require.False(t, mapping.Mapped)
  1058. require.Equal(t, "claude-opus-4", mapping.MappedModel)
  1059. }
  1060. func TestResolveChannelMappingAndRestrict_WithMapping(t *testing.T) {
  1061. ch := Channel{
  1062. ID: 1,
  1063. Status: StatusActive,
  1064. GroupIDs: []int64{10},
  1065. RestrictModels: true,
  1066. ModelPricing: []ChannelModelPricing{
  1067. {Platform: "anthropic", Models: []string{"claude-sonnet-4"}},
  1068. },
  1069. ModelMapping: map[string]map[string]string{
  1070. "anthropic": {
  1071. "claude-sonnet-4": "claude-sonnet-4-20250514",
  1072. },
  1073. },
  1074. }
  1075. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  1076. svc := newTestChannelService(repo)
  1077. gid := int64(10)
  1078. mapping, restricted := svc.ResolveChannelMappingAndRestrict(context.Background(), &gid, "claude-sonnet-4")
  1079. require.False(t, restricted) // restricted 始终为 false,限制检查在调度阶段
  1080. require.True(t, mapping.Mapped)
  1081. require.Equal(t, "claude-sonnet-4-20250514", mapping.MappedModel)
  1082. }
  1083. func TestResolveChannelMappingAndRestrict_NoMapping(t *testing.T) {
  1084. ch := Channel{
  1085. ID: 1,
  1086. Status: StatusActive,
  1087. GroupIDs: []int64{10},
  1088. RestrictModels: true,
  1089. ModelPricing: []ChannelModelPricing{
  1090. {Platform: "anthropic", Models: []string{"claude-sonnet-4"}},
  1091. },
  1092. }
  1093. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  1094. svc := newTestChannelService(repo)
  1095. gid := int64(10)
  1096. mapping, restricted := svc.ResolveChannelMappingAndRestrict(context.Background(), &gid, "unknown-model")
  1097. require.False(t, restricted) // restricted 始终为 false,限制检查在调度阶段
  1098. require.False(t, mapping.Mapped)
  1099. require.Equal(t, "unknown-model", mapping.MappedModel)
  1100. }
  1101. // --- 4.6 Cache Building Specifics ---
  1102. func TestBuildCache_DBError(t *testing.T) {
  1103. callCount := 0
  1104. repo := &mockChannelRepository{
  1105. listAllFn: func(_ context.Context) ([]Channel, error) {
  1106. callCount++
  1107. return nil, errors.New("database down")
  1108. },
  1109. }
  1110. svc := newTestChannelService(repo)
  1111. // First call should fail
  1112. _, err := svc.GetChannelForGroup(context.Background(), 10)
  1113. require.Error(t, err)
  1114. require.Contains(t, err.Error(), "database down")
  1115. require.Equal(t, 1, callCount)
  1116. // Second call within error-TTL should use error cache, but still return error
  1117. // Because buildCache stores error-TTL cache and returns error, the cached value
  1118. // is still within TTL and loadCache returns it (which is an empty cache).
  1119. // Actually, re-reading the code: buildCache returns nil, err, and the error cache
  1120. // only serves as a "don't retry immediately" mechanism. The singleflight.Do
  1121. // returns the error. On next call within error-TTL, the cache has an empty but
  1122. // valid entry, so loadCache returns it (with empty maps). GetChannelForGroup
  1123. // will find nothing and return nil, nil.
  1124. result, err := svc.GetChannelForGroup(context.Background(), 10)
  1125. require.NoError(t, err)
  1126. require.Nil(t, result)
  1127. // Should NOT have hit DB again (error-TTL cache is active)
  1128. require.Equal(t, 1, callCount)
  1129. }
  1130. func TestBuildCache_GroupPlatformError(t *testing.T) {
  1131. ch := Channel{
  1132. ID: 1,
  1133. Status: StatusActive,
  1134. GroupIDs: []int64{10},
  1135. ModelPricing: []ChannelModelPricing{
  1136. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1137. },
  1138. }
  1139. repo := &mockChannelRepository{
  1140. listAllFn: func(_ context.Context) ([]Channel, error) {
  1141. return []Channel{ch}, nil
  1142. },
  1143. getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
  1144. return nil, errors.New("group platforms failed")
  1145. },
  1146. }
  1147. svc := newTestChannelService(repo)
  1148. // Should fail-close: error propagated when group platforms cannot be loaded
  1149. result, err := svc.GetChannelForGroup(context.Background(), 10)
  1150. require.Error(t, err)
  1151. require.Nil(t, result)
  1152. // Within error-TTL, second call should hit cache (empty) and return nil, nil
  1153. result2, err2 := svc.GetChannelForGroup(context.Background(), 10)
  1154. require.NoError(t, err2)
  1155. require.Nil(t, result2)
  1156. }
  1157. func TestBuildCache_MultipleGroupsSameChannel(t *testing.T) {
  1158. ch := Channel{
  1159. ID: 1,
  1160. Status: StatusActive,
  1161. GroupIDs: []int64{10, 20, 30},
  1162. ModelPricing: []ChannelModelPricing{
  1163. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}, InputPrice: testPtrFloat64(15e-6)},
  1164. },
  1165. }
  1166. repo := makeStandardRepo(ch, map[int64]string{
  1167. 10: "anthropic",
  1168. 20: "anthropic",
  1169. 30: "anthropic",
  1170. })
  1171. svc := newTestChannelService(repo)
  1172. for _, gid := range []int64{10, 20, 30} {
  1173. result := svc.GetChannelModelPricing(context.Background(), gid, "claude-opus-4")
  1174. require.NotNil(t, result, "group %d should have pricing", gid)
  1175. require.Equal(t, int64(100), result.ID)
  1176. }
  1177. }
  1178. func TestBuildCache_PlatformFiltering(t *testing.T) {
  1179. ch := Channel{
  1180. ID: 1,
  1181. Status: StatusActive,
  1182. GroupIDs: []int64{10, 20},
  1183. ModelPricing: []ChannelModelPricing{
  1184. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1185. {ID: 200, Platform: "openai", Models: []string{"gpt-5.1"}},
  1186. },
  1187. }
  1188. repo := makeStandardRepo(ch, map[int64]string{
  1189. 10: "anthropic",
  1190. 20: "openai",
  1191. })
  1192. svc := newTestChannelService(repo)
  1193. // anthropic group sees only anthropic models
  1194. require.NotNil(t, svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4"))
  1195. require.Nil(t, svc.GetChannelModelPricing(context.Background(), 10, "gpt-5.1"))
  1196. // openai group sees only openai models
  1197. require.NotNil(t, svc.GetChannelModelPricing(context.Background(), 20, "gpt-5.1"))
  1198. require.Nil(t, svc.GetChannelModelPricing(context.Background(), 20, "claude-opus-4"))
  1199. }
  1200. func TestBuildCache_WildcardPreservesConfigOrder(t *testing.T) {
  1201. ch := Channel{
  1202. ID: 1,
  1203. Status: StatusActive,
  1204. GroupIDs: []int64{10},
  1205. ModelPricing: []ChannelModelPricing{
  1206. // Configuration order: shortest prefix first
  1207. {ID: 100, Platform: "anthropic", Models: []string{"c-*"}, InputPrice: testPtrFloat64(1e-6)},
  1208. {ID: 200, Platform: "anthropic", Models: []string{"c-son-*"}, InputPrice: testPtrFloat64(2e-6)},
  1209. {ID: 300, Platform: "anthropic", Models: []string{"c-son-4-*"}, InputPrice: testPtrFloat64(3e-6)},
  1210. },
  1211. }
  1212. repo := makeStandardRepo(ch, map[int64]string{10: "anthropic"})
  1213. svc := newTestChannelService(repo)
  1214. // "c-son-4-xxx" matches all three wildcards, but "c-*" (ID=100) is first in config
  1215. result := svc.GetChannelModelPricing(context.Background(), 10, "c-son-4-xxx")
  1216. require.NotNil(t, result)
  1217. require.Equal(t, int64(100), result.ID)
  1218. // "c-son-yyy" matches "c-*" and "c-son-*", but "c-*" (ID=100) is first
  1219. result = svc.GetChannelModelPricing(context.Background(), 10, "c-son-yyy")
  1220. require.NotNil(t, result)
  1221. require.Equal(t, int64(100), result.ID)
  1222. // "c-other" only matches "c-*" (ID=100)
  1223. result = svc.GetChannelModelPricing(context.Background(), 10, "c-other")
  1224. require.NotNil(t, result)
  1225. require.Equal(t, int64(100), result.ID)
  1226. }
  1227. // --- 4.7 invalidateCache ---
  1228. func TestInvalidateCache(t *testing.T) {
  1229. callCount := 0
  1230. ch := Channel{
  1231. ID: 1,
  1232. Status: StatusActive,
  1233. GroupIDs: []int64{10},
  1234. ModelPricing: []ChannelModelPricing{
  1235. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1236. },
  1237. }
  1238. repo := &mockChannelRepository{
  1239. listAllFn: func(_ context.Context) ([]Channel, error) {
  1240. callCount++
  1241. return []Channel{ch}, nil
  1242. },
  1243. getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
  1244. return map[int64]string{10: "anthropic"}, nil
  1245. },
  1246. }
  1247. svc := newTestChannelService(repo)
  1248. // First load
  1249. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  1250. require.NotNil(t, result)
  1251. require.Equal(t, 1, callCount)
  1252. // Second call should use cache
  1253. result = svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  1254. require.NotNil(t, result)
  1255. require.Equal(t, 1, callCount) // no new DB call
  1256. // Invalidate
  1257. svc.invalidateCache()
  1258. // Next call should rebuild from DB
  1259. result = svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  1260. require.NotNil(t, result)
  1261. require.Equal(t, 2, callCount) // rebuilt
  1262. }
  1263. func TestInvalidateCachePublishesToOtherInstances(t *testing.T) {
  1264. cachePubSub := &mockChannelCachePubSub{}
  1265. publisher := NewChannelService(&mockChannelRepository{}, nil, nil, nil, cachePubSub)
  1266. updated := false
  1267. subscriberRepo := &mockChannelRepository{
  1268. listAllFn: func(_ context.Context) ([]Channel, error) {
  1269. model := "old-model"
  1270. if updated {
  1271. model = "new-model"
  1272. }
  1273. return []Channel{{
  1274. ID: 1,
  1275. Status: StatusActive,
  1276. GroupIDs: []int64{10},
  1277. ModelPricing: []ChannelModelPricing{{
  1278. ID: 100,
  1279. Platform: PlatformAnthropic,
  1280. Models: []string{model},
  1281. }},
  1282. }}, nil
  1283. },
  1284. getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
  1285. return map[int64]string{10: PlatformAnthropic}, nil
  1286. },
  1287. }
  1288. subscriber := NewChannelService(subscriberRepo, nil, nil, nil, cachePubSub)
  1289. require.NotNil(t, subscriber.GetChannelModelPricing(context.Background(), 10, "old-model"))
  1290. require.Nil(t, subscriber.GetChannelModelPricing(context.Background(), 10, "new-model"))
  1291. updated = true
  1292. publisher.invalidateCache()
  1293. require.NotNil(t, subscriber.GetChannelModelPricing(context.Background(), 10, "new-model"))
  1294. }
  1295. // ===========================================================================
  1296. // 5. CRUD Methods
  1297. // ===========================================================================
  1298. // --- 5.1 Create ---
  1299. func TestCreate_Success(t *testing.T) {
  1300. createdID := int64(42)
  1301. repo := &mockChannelRepository{
  1302. existsByNameFn: func(_ context.Context, _ string) (bool, error) {
  1303. return false, nil
  1304. },
  1305. getGroupsInOtherChannelsFn: func(_ context.Context, _ int64, _ []int64) ([]int64, error) {
  1306. return nil, nil
  1307. },
  1308. createFn: func(_ context.Context, ch *Channel) error {
  1309. ch.ID = createdID
  1310. return nil
  1311. },
  1312. getByIDFn: func(_ context.Context, id int64) (*Channel, error) {
  1313. return &Channel{ID: id, Name: "new-channel", Status: StatusActive}, nil
  1314. },
  1315. listAllFn: func(_ context.Context) ([]Channel, error) {
  1316. return nil, nil
  1317. },
  1318. }
  1319. svc := newTestChannelService(repo)
  1320. result, err := svc.Create(context.Background(), &CreateChannelInput{
  1321. Name: "new-channel",
  1322. GroupIDs: []int64{10},
  1323. })
  1324. require.NoError(t, err)
  1325. require.NotNil(t, result)
  1326. require.Equal(t, createdID, result.ID)
  1327. }
  1328. func TestCreate_NameExists(t *testing.T) {
  1329. repo := &mockChannelRepository{
  1330. existsByNameFn: func(_ context.Context, _ string) (bool, error) {
  1331. return true, nil
  1332. },
  1333. }
  1334. svc := newTestChannelService(repo)
  1335. _, err := svc.Create(context.Background(), &CreateChannelInput{
  1336. Name: "existing-channel",
  1337. })
  1338. require.Error(t, err)
  1339. require.ErrorIs(t, err, ErrChannelExists)
  1340. }
  1341. func TestCreate_GroupConflict(t *testing.T) {
  1342. repo := &mockChannelRepository{
  1343. existsByNameFn: func(_ context.Context, _ string) (bool, error) {
  1344. return false, nil
  1345. },
  1346. getGroupsInOtherChannelsFn: func(_ context.Context, _ int64, _ []int64) ([]int64, error) {
  1347. return []int64{10}, nil // group 10 already in another channel
  1348. },
  1349. }
  1350. svc := newTestChannelService(repo)
  1351. _, err := svc.Create(context.Background(), &CreateChannelInput{
  1352. Name: "new-channel",
  1353. GroupIDs: []int64{10, 20},
  1354. })
  1355. require.Error(t, err)
  1356. require.ErrorIs(t, err, ErrGroupAlreadyInChannel)
  1357. }
  1358. func TestCreate_DuplicateModel(t *testing.T) {
  1359. repo := &mockChannelRepository{
  1360. existsByNameFn: func(_ context.Context, _ string) (bool, error) {
  1361. return false, nil
  1362. },
  1363. }
  1364. svc := newTestChannelService(repo)
  1365. _, err := svc.Create(context.Background(), &CreateChannelInput{
  1366. Name: "new-channel",
  1367. ModelPricing: []ChannelModelPricing{
  1368. {Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1369. {Platform: "anthropic", Models: []string{"claude-opus-4"}}, // duplicate
  1370. },
  1371. })
  1372. require.Error(t, err)
  1373. require.Contains(t, err.Error(), "claude-opus-4")
  1374. }
  1375. func TestCreate_InvalidPricingIntervals(t *testing.T) {
  1376. repo := &mockChannelRepository{
  1377. existsByNameFn: func(_ context.Context, _ string) (bool, error) {
  1378. return false, nil
  1379. },
  1380. }
  1381. svc := newTestChannelService(repo)
  1382. _, err := svc.Create(context.Background(), &CreateChannelInput{
  1383. Name: "new-channel",
  1384. ModelPricing: []ChannelModelPricing{
  1385. {
  1386. Platform: "anthropic",
  1387. Models: []string{"claude-opus-4"},
  1388. Intervals: []PricingInterval{
  1389. {MinTokens: 0, MaxTokens: testPtrInt(2000), InputPrice: testPtrFloat64(1e-6)},
  1390. {MinTokens: 1000, MaxTokens: testPtrInt(3000), InputPrice: testPtrFloat64(2e-6)},
  1391. },
  1392. },
  1393. },
  1394. })
  1395. require.Error(t, err)
  1396. require.Contains(t, err.Error(), "INVALID_PRICING_INTERVALS")
  1397. require.Contains(t, err.Error(), "overlap")
  1398. }
  1399. func TestCreate_DefaultBillingModelSource(t *testing.T) {
  1400. var capturedChannel *Channel
  1401. repo := &mockChannelRepository{
  1402. existsByNameFn: func(_ context.Context, _ string) (bool, error) {
  1403. return false, nil
  1404. },
  1405. createFn: func(_ context.Context, ch *Channel) error {
  1406. capturedChannel = ch
  1407. ch.ID = 1
  1408. return nil
  1409. },
  1410. getByIDFn: func(_ context.Context, id int64) (*Channel, error) {
  1411. return capturedChannel, nil
  1412. },
  1413. listAllFn: func(_ context.Context) ([]Channel, error) {
  1414. return nil, nil
  1415. },
  1416. }
  1417. svc := newTestChannelService(repo)
  1418. result, err := svc.Create(context.Background(), &CreateChannelInput{
  1419. Name: "new-channel",
  1420. BillingModelSource: "", // empty, should default to "channel_mapped"
  1421. })
  1422. require.NoError(t, err)
  1423. require.NotNil(t, result)
  1424. require.Equal(t, BillingModelSourceChannelMapped, result.BillingModelSource)
  1425. }
  1426. func TestCreate_InvalidatesCache(t *testing.T) {
  1427. loadCount := 0
  1428. ch := Channel{
  1429. ID: 1,
  1430. Status: StatusActive,
  1431. GroupIDs: []int64{10},
  1432. ModelPricing: []ChannelModelPricing{
  1433. {ID: 100, Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1434. },
  1435. }
  1436. repo := &mockChannelRepository{
  1437. listAllFn: func(_ context.Context) ([]Channel, error) {
  1438. loadCount++
  1439. return []Channel{ch}, nil
  1440. },
  1441. getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
  1442. return map[int64]string{10: "anthropic"}, nil
  1443. },
  1444. existsByNameFn: func(_ context.Context, _ string) (bool, error) {
  1445. return false, nil
  1446. },
  1447. createFn: func(_ context.Context, c *Channel) error {
  1448. c.ID = 2
  1449. return nil
  1450. },
  1451. getByIDFn: func(_ context.Context, id int64) (*Channel, error) {
  1452. return &Channel{ID: id, Name: "new", Status: StatusActive}, nil
  1453. },
  1454. }
  1455. svc := newTestChannelService(repo)
  1456. // Load cache
  1457. _ = svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  1458. require.Equal(t, 1, loadCount)
  1459. // Create triggers cache invalidation
  1460. _, err := svc.Create(context.Background(), &CreateChannelInput{Name: "new"})
  1461. require.NoError(t, err)
  1462. // Next cache access should rebuild
  1463. _ = svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4")
  1464. require.Equal(t, 2, loadCount)
  1465. }
  1466. // --- 5.2 Update ---
  1467. func TestUpdate_Success(t *testing.T) {
  1468. existing := &Channel{
  1469. ID: 1,
  1470. Name: "original",
  1471. Status: StatusActive,
  1472. }
  1473. repo := &mockChannelRepository{
  1474. getByIDFn: func(_ context.Context, id int64) (*Channel, error) {
  1475. return existing.Clone(), nil
  1476. },
  1477. updateFn: func(_ context.Context, _ *Channel) error {
  1478. return nil
  1479. },
  1480. getGroupIDsFn: func(_ context.Context, _ int64) ([]int64, error) {
  1481. return nil, nil
  1482. },
  1483. listAllFn: func(_ context.Context) ([]Channel, error) {
  1484. return nil, nil
  1485. },
  1486. }
  1487. svc := newTestChannelService(repo)
  1488. result, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  1489. Name: "updated-name",
  1490. Description: testPtrString("new desc"),
  1491. })
  1492. require.NoError(t, err)
  1493. require.NotNil(t, result)
  1494. }
  1495. func TestUpdate_NotFound(t *testing.T) {
  1496. repo := &mockChannelRepository{
  1497. getByIDFn: func(_ context.Context, _ int64) (*Channel, error) {
  1498. return nil, ErrChannelNotFound
  1499. },
  1500. }
  1501. svc := newTestChannelService(repo)
  1502. _, err := svc.Update(context.Background(), 999, &UpdateChannelInput{
  1503. Name: "whatever",
  1504. })
  1505. require.Error(t, err)
  1506. require.Contains(t, err.Error(), "channel")
  1507. }
  1508. func TestUpdate_NameConflict(t *testing.T) {
  1509. existing := &Channel{
  1510. ID: 1,
  1511. Name: "original",
  1512. Status: StatusActive,
  1513. }
  1514. repo := &mockChannelRepository{
  1515. getByIDFn: func(_ context.Context, _ int64) (*Channel, error) {
  1516. return existing.Clone(), nil
  1517. },
  1518. existsByNameExcludingFn: func(_ context.Context, _ string, _ int64) (bool, error) {
  1519. return true, nil // name conflicts with another channel
  1520. },
  1521. }
  1522. svc := newTestChannelService(repo)
  1523. _, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  1524. Name: "conflicting-name",
  1525. })
  1526. require.Error(t, err)
  1527. require.ErrorIs(t, err, ErrChannelExists)
  1528. }
  1529. func TestUpdate_GroupConflict(t *testing.T) {
  1530. existing := &Channel{
  1531. ID: 1,
  1532. Name: "original",
  1533. Status: StatusActive,
  1534. }
  1535. repo := &mockChannelRepository{
  1536. getByIDFn: func(_ context.Context, _ int64) (*Channel, error) {
  1537. return existing.Clone(), nil
  1538. },
  1539. getGroupsInOtherChannelsFn: func(_ context.Context, _ int64, _ []int64) ([]int64, error) {
  1540. return []int64{20}, nil // group 20 in another channel
  1541. },
  1542. }
  1543. svc := newTestChannelService(repo)
  1544. newGroupIDs := []int64{10, 20}
  1545. _, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  1546. GroupIDs: &newGroupIDs,
  1547. })
  1548. require.Error(t, err)
  1549. require.ErrorIs(t, err, ErrGroupAlreadyInChannel)
  1550. }
  1551. func TestUpdate_DuplicateModel(t *testing.T) {
  1552. existing := &Channel{
  1553. ID: 1,
  1554. Name: "original",
  1555. Status: StatusActive,
  1556. }
  1557. repo := &mockChannelRepository{
  1558. getByIDFn: func(_ context.Context, _ int64) (*Channel, error) {
  1559. return existing.Clone(), nil
  1560. },
  1561. }
  1562. svc := newTestChannelService(repo)
  1563. dupPricing := []ChannelModelPricing{
  1564. {Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1565. {Platform: "anthropic", Models: []string{"claude-opus-4"}},
  1566. }
  1567. _, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  1568. ModelPricing: &dupPricing,
  1569. })
  1570. require.Error(t, err)
  1571. require.Contains(t, err.Error(), "claude-opus-4")
  1572. }
  1573. func TestUpdate_InvalidPricingIntervals(t *testing.T) {
  1574. existing := &Channel{
  1575. ID: 1,
  1576. Name: "original",
  1577. Status: StatusActive,
  1578. }
  1579. repo := &mockChannelRepository{
  1580. getByIDFn: func(_ context.Context, _ int64) (*Channel, error) {
  1581. return existing.Clone(), nil
  1582. },
  1583. }
  1584. svc := newTestChannelService(repo)
  1585. invalidPricing := []ChannelModelPricing{
  1586. {
  1587. Platform: "anthropic",
  1588. Models: []string{"claude-opus-4"},
  1589. Intervals: []PricingInterval{
  1590. {MinTokens: 0, MaxTokens: nil, InputPrice: testPtrFloat64(1e-6)},
  1591. {MinTokens: 2000, MaxTokens: testPtrInt(4000), InputPrice: testPtrFloat64(2e-6)},
  1592. },
  1593. },
  1594. }
  1595. _, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  1596. ModelPricing: &invalidPricing,
  1597. })
  1598. require.Error(t, err)
  1599. require.Contains(t, err.Error(), "INVALID_PRICING_INTERVALS")
  1600. require.Contains(t, err.Error(), "unbounded")
  1601. }
  1602. func TestUpdate_InvalidatesChannelCache(t *testing.T) {
  1603. existing := &Channel{
  1604. ID: 1,
  1605. Name: "original",
  1606. Status: StatusActive,
  1607. }
  1608. loadCount := 0
  1609. repo := &mockChannelRepository{
  1610. getByIDFn: func(_ context.Context, _ int64) (*Channel, error) {
  1611. return existing.Clone(), nil
  1612. },
  1613. updateFn: func(_ context.Context, _ *Channel) error {
  1614. return nil
  1615. },
  1616. getGroupIDsFn: func(_ context.Context, _ int64) ([]int64, error) {
  1617. return []int64{10, 20}, nil
  1618. },
  1619. listAllFn: func(_ context.Context) ([]Channel, error) {
  1620. loadCount++
  1621. return []Channel{*existing}, nil
  1622. },
  1623. getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
  1624. return nil, nil
  1625. },
  1626. }
  1627. svc := newTestChannelService(repo)
  1628. // Load cache first
  1629. _, _ = svc.GetChannelForGroup(context.Background(), 10)
  1630. require.Equal(t, 1, loadCount)
  1631. result, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  1632. Description: testPtrString("updated"),
  1633. })
  1634. require.NoError(t, err)
  1635. require.NotNil(t, result)
  1636. // Channel cache should be invalidated (next access rebuilds)
  1637. _, _ = svc.GetChannelForGroup(context.Background(), 10)
  1638. require.Equal(t, 2, loadCount)
  1639. }
  1640. func TestUpdate_InvalidatesAuthCache(t *testing.T) {
  1641. existing := &Channel{
  1642. ID: 1,
  1643. Name: "original",
  1644. Status: StatusActive,
  1645. }
  1646. auth := &mockChannelAuthCacheInvalidator{}
  1647. repo := &mockChannelRepository{
  1648. getByIDFn: func(_ context.Context, _ int64) (*Channel, error) {
  1649. return existing.Clone(), nil
  1650. },
  1651. updateFn: func(_ context.Context, _ *Channel) error {
  1652. return nil
  1653. },
  1654. getGroupIDsFn: func(_ context.Context, _ int64) ([]int64, error) {
  1655. return []int64{10, 20}, nil
  1656. },
  1657. listAllFn: func(_ context.Context) ([]Channel, error) {
  1658. return nil, nil
  1659. },
  1660. }
  1661. svc := newTestChannelServiceWithAuth(repo, auth)
  1662. result, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  1663. Description: testPtrString("updated"),
  1664. })
  1665. require.NoError(t, err)
  1666. require.NotNil(t, result)
  1667. // Auth cache should be invalidated for both groups
  1668. require.ElementsMatch(t, []int64{10, 20}, auth.invalidatedGroupIDs)
  1669. }
  1670. // --- 5.3 Delete ---
  1671. func TestChannelDelete_Success(t *testing.T) {
  1672. deleted := false
  1673. repo := &mockChannelRepository{
  1674. getGroupIDsFn: func(_ context.Context, _ int64) ([]int64, error) {
  1675. return nil, nil
  1676. },
  1677. deleteFn: func(_ context.Context, _ int64) error {
  1678. deleted = true
  1679. return nil
  1680. },
  1681. listAllFn: func(_ context.Context) ([]Channel, error) {
  1682. return nil, nil
  1683. },
  1684. }
  1685. svc := newTestChannelService(repo)
  1686. err := svc.Delete(context.Background(), 1)
  1687. require.NoError(t, err)
  1688. require.True(t, deleted)
  1689. }
  1690. func TestChannelDelete_InvalidatesCaches(t *testing.T) {
  1691. auth := &mockChannelAuthCacheInvalidator{}
  1692. loadCount := 0
  1693. repo := &mockChannelRepository{
  1694. getGroupIDsFn: func(_ context.Context, _ int64) ([]int64, error) {
  1695. return []int64{10, 20}, nil
  1696. },
  1697. deleteFn: func(_ context.Context, _ int64) error {
  1698. return nil
  1699. },
  1700. listAllFn: func(_ context.Context) ([]Channel, error) {
  1701. loadCount++
  1702. return []Channel{{ID: 1, Status: StatusActive, GroupIDs: []int64{10, 20}}}, nil
  1703. },
  1704. getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
  1705. return nil, nil
  1706. },
  1707. }
  1708. svc := newTestChannelServiceWithAuth(repo, auth)
  1709. // Load cache first
  1710. _, _ = svc.GetChannelForGroup(context.Background(), 10)
  1711. require.Equal(t, 1, loadCount)
  1712. err := svc.Delete(context.Background(), 1)
  1713. require.NoError(t, err)
  1714. // Auth cache invalidated for both groups
  1715. require.ElementsMatch(t, []int64{10, 20}, auth.invalidatedGroupIDs)
  1716. // Channel cache invalidated
  1717. _, _ = svc.GetChannelForGroup(context.Background(), 10)
  1718. require.Equal(t, 2, loadCount)
  1719. }
  1720. func TestChannelDelete_NotFound(t *testing.T) {
  1721. repo := &mockChannelRepository{
  1722. getGroupIDsFn: func(_ context.Context, _ int64) ([]int64, error) {
  1723. return nil, nil
  1724. },
  1725. deleteFn: func(_ context.Context, _ int64) error {
  1726. return errors.New("record not found")
  1727. },
  1728. }
  1729. svc := newTestChannelService(repo)
  1730. err := svc.Delete(context.Background(), 999)
  1731. require.Error(t, err)
  1732. require.Contains(t, err.Error(), "not found")
  1733. }
  1734. // ===========================================================================
  1735. // 6. Edge Case Tests
  1736. // ===========================================================================
  1737. // --- 6.1 Create with empty GroupIDs ---
  1738. func TestCreate_NoGroups(t *testing.T) {
  1739. createdID := int64(55)
  1740. getGroupsInOtherChannelsCalled := false
  1741. repo := &mockChannelRepository{
  1742. existsByNameFn: func(_ context.Context, _ string) (bool, error) {
  1743. return false, nil
  1744. },
  1745. getGroupsInOtherChannelsFn: func(_ context.Context, _ int64, _ []int64) ([]int64, error) {
  1746. getGroupsInOtherChannelsCalled = true
  1747. return nil, nil
  1748. },
  1749. createFn: func(_ context.Context, ch *Channel) error {
  1750. ch.ID = createdID
  1751. return nil
  1752. },
  1753. getByIDFn: func(_ context.Context, id int64) (*Channel, error) {
  1754. return &Channel{ID: id, Name: "no-groups-channel", Status: StatusActive}, nil
  1755. },
  1756. listAllFn: func(_ context.Context) ([]Channel, error) {
  1757. return nil, nil
  1758. },
  1759. }
  1760. svc := newTestChannelService(repo)
  1761. result, err := svc.Create(context.Background(), &CreateChannelInput{
  1762. Name: "no-groups-channel",
  1763. GroupIDs: []int64{}, // empty slice
  1764. })
  1765. require.NoError(t, err)
  1766. require.NotNil(t, result)
  1767. require.Equal(t, createdID, result.ID)
  1768. // GetGroupsInOtherChannels should NOT have been called (skipped by len(input.GroupIDs) > 0)
  1769. require.False(t, getGroupsInOtherChannelsCalled)
  1770. }
  1771. // --- 6.2 Update only Status ---
  1772. func TestUpdate_StatusOnly(t *testing.T) {
  1773. existing := &Channel{
  1774. ID: 1,
  1775. Name: "test-channel",
  1776. Status: StatusActive,
  1777. }
  1778. var capturedChannel *Channel
  1779. repo := &mockChannelRepository{
  1780. getByIDFn: func(_ context.Context, id int64) (*Channel, error) {
  1781. return existing.Clone(), nil
  1782. },
  1783. updateFn: func(_ context.Context, ch *Channel) error {
  1784. capturedChannel = ch
  1785. return nil
  1786. },
  1787. getGroupIDsFn: func(_ context.Context, _ int64) ([]int64, error) {
  1788. return nil, nil
  1789. },
  1790. listAllFn: func(_ context.Context) ([]Channel, error) {
  1791. return nil, nil
  1792. },
  1793. }
  1794. svc := newTestChannelService(repo)
  1795. result, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  1796. Status: StatusDisabled,
  1797. })
  1798. require.NoError(t, err)
  1799. require.NotNil(t, result)
  1800. // Verify that the channel passed to repo.Update has the new status
  1801. require.NotNil(t, capturedChannel)
  1802. require.Equal(t, StatusDisabled, capturedChannel.Status)
  1803. // Name should remain unchanged
  1804. require.Equal(t, "test-channel", capturedChannel.Name)
  1805. }
  1806. // --- 6.3 Delete when GetGroupIDs fails ---
  1807. func TestChannelDelete_GetGroupIDsError(t *testing.T) {
  1808. deleted := false
  1809. repo := &mockChannelRepository{
  1810. getGroupIDsFn: func(_ context.Context, _ int64) ([]int64, error) {
  1811. return nil, errors.New("group IDs lookup failed")
  1812. },
  1813. deleteFn: func(_ context.Context, _ int64) error {
  1814. deleted = true
  1815. return nil
  1816. },
  1817. listAllFn: func(_ context.Context) ([]Channel, error) {
  1818. return nil, nil
  1819. },
  1820. }
  1821. svc := newTestChannelService(repo)
  1822. // Delete should still succeed even though GetGroupIDs returned error (degradation path L588-591)
  1823. err := svc.Delete(context.Background(), 1)
  1824. require.NoError(t, err)
  1825. require.True(t, deleted)
  1826. }
  1827. // --- 6.4 ReplaceModelInBody with invalid JSON ---
  1828. func TestReplaceModelInBody_InvalidJSON(t *testing.T) {
  1829. // Case 1: broken JSON object — gjson won't find "model", sjson does best-effort set
  1830. // (no panic, no error from sjson, but result is mutated garbage)
  1831. brokenBody := []byte("{broken")
  1832. result := ReplaceModelInBody(brokenBody, "new-model")
  1833. require.NotNil(t, result)
  1834. // sjson does not error on this input, so result differs from original — just verify no panic
  1835. // Case 2: JSON array — sjson.SetBytes returns error on non-object,
  1836. // triggering the L447 error fallback path that returns original body.
  1837. arrayBody := []byte("[]")
  1838. result2 := ReplaceModelInBody(arrayBody, "new-model")
  1839. require.Equal(t, arrayBody, result2)
  1840. }
  1841. func TestRemovePreviousResponseIDFromBody(t *testing.T) {
  1842. t.Run("empty body returned as-is", func(t *testing.T) {
  1843. require.Equal(t, []byte{}, RemovePreviousResponseIDFromBody([]byte{}))
  1844. require.Nil(t, RemovePreviousResponseIDFromBody(nil))
  1845. })
  1846. t.Run("no previous_response_id field is a no-op", func(t *testing.T) {
  1847. body := []byte(`{"model":"gpt-5","input":"hi"}`)
  1848. result := RemovePreviousResponseIDFromBody(body)
  1849. require.Equal(t, body, result)
  1850. })
  1851. t.Run("strips previous_response_id and preserves other fields", func(t *testing.T) {
  1852. body := []byte(`{"model":"gpt-5","previous_response_id":"resp_abc","input":"hi"}`)
  1853. result := RemovePreviousResponseIDFromBody(body)
  1854. require.False(t, gjson.GetBytes(result, "previous_response_id").Exists())
  1855. require.Equal(t, "gpt-5", gjson.GetBytes(result, "model").String())
  1856. require.Equal(t, "hi", gjson.GetBytes(result, "input").String())
  1857. })
  1858. t.Run("empty-string previous_response_id is also stripped", func(t *testing.T) {
  1859. body := []byte(`{"model":"gpt-5","previous_response_id":""}`)
  1860. result := RemovePreviousResponseIDFromBody(body)
  1861. require.False(t, gjson.GetBytes(result, "previous_response_id").Exists())
  1862. })
  1863. }
  1864. // ===========================================================================
  1865. // 7. isPlatformPricingMatch
  1866. // ===========================================================================
  1867. func TestIsPlatformPricingMatch(t *testing.T) {
  1868. tests := []struct {
  1869. name string
  1870. groupPlatform string
  1871. pricingPlatform string
  1872. want bool
  1873. }{
  1874. {"antigravity does NOT match anthropic", PlatformAntigravity, PlatformAnthropic, false},
  1875. {"antigravity does NOT match gemini", PlatformAntigravity, PlatformGemini, false},
  1876. {"antigravity matches antigravity", PlatformAntigravity, PlatformAntigravity, true},
  1877. {"antigravity does NOT match openai", PlatformAntigravity, PlatformOpenAI, false},
  1878. {"anthropic matches anthropic", PlatformAnthropic, PlatformAnthropic, true},
  1879. {"anthropic does NOT match antigravity", PlatformAnthropic, PlatformAntigravity, false},
  1880. {"anthropic does NOT match gemini", PlatformAnthropic, PlatformGemini, false},
  1881. {"gemini matches gemini", PlatformGemini, PlatformGemini, true},
  1882. {"gemini does NOT match antigravity", PlatformGemini, PlatformAntigravity, false},
  1883. {"gemini does NOT match anthropic", PlatformGemini, PlatformAnthropic, false},
  1884. {"composite matches openai pricing", PlatformComposite, PlatformOpenAI, true},
  1885. {"composite matches gemini pricing", PlatformComposite, PlatformGemini, true},
  1886. {"composite matches kimi pricing", PlatformComposite, PlatformKimi, true},
  1887. {"composite matches zhipu pricing", PlatformComposite, PlatformZhipu, true},
  1888. {"composite matches deepseek pricing", PlatformComposite, PlatformDeepseek, true},
  1889. {"empty string matches nothing", "", PlatformAnthropic, false},
  1890. {"empty string matches empty", "", "", true},
  1891. }
  1892. for _, tt := range tests {
  1893. t.Run(tt.name, func(t *testing.T) {
  1894. require.Equal(t, tt.want, isPlatformPricingMatch(tt.groupPlatform, tt.pricingPlatform))
  1895. })
  1896. }
  1897. }
  1898. // ===========================================================================
  1899. // 8. matchingPlatforms
  1900. // ===========================================================================
  1901. func TestMatchingPlatforms(t *testing.T) {
  1902. tests := []struct {
  1903. name string
  1904. groupPlatform string
  1905. want []string
  1906. }{
  1907. {"antigravity returns itself only", PlatformAntigravity, []string{PlatformAntigravity}},
  1908. {"anthropic returns itself", PlatformAnthropic, []string{PlatformAnthropic}},
  1909. {"gemini returns itself", PlatformGemini, []string{PlatformGemini}},
  1910. {"openai returns itself", PlatformOpenAI, []string{PlatformOpenAI}},
  1911. {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax}},
  1912. }
  1913. for _, tt := range tests {
  1914. t.Run(tt.name, func(t *testing.T) {
  1915. result := matchingPlatforms(tt.groupPlatform)
  1916. require.Equal(t, tt.want, result)
  1917. })
  1918. }
  1919. }
  1920. func TestCompositeChannelLookupUsesResolvedTargetPlatform(t *testing.T) {
  1921. channel := Channel{
  1922. ID: 1,
  1923. Status: StatusActive,
  1924. GroupIDs: []int64{99},
  1925. ModelPricing: []ChannelModelPricing{
  1926. {Platform: PlatformOpenAI, Models: []string{"gpt-*"}},
  1927. {Platform: PlatformAnthropic, Models: []string{"claude-*"}},
  1928. },
  1929. ModelMapping: map[string]map[string]string{
  1930. PlatformOpenAI: {
  1931. "gpt-5": "gpt-5-mini",
  1932. },
  1933. PlatformAnthropic: {
  1934. "claude-*": "claude-sonnet-4-5",
  1935. },
  1936. },
  1937. }
  1938. cache := populateChannelCache([]Channel{channel}, map[int64]string{99: PlatformComposite})
  1939. svc := &ChannelService{}
  1940. svc.cache.Store(cache)
  1941. openAICtx := WithResolvedTargetPlatform(context.Background(), PlatformOpenAI)
  1942. require.NotNil(t, svc.GetChannelModelPricing(openAICtx, 99, "gpt-5"))
  1943. require.Nil(t, svc.GetChannelModelPricing(openAICtx, 99, "claude-sonnet-4-5"))
  1944. openAIResult := svc.ResolveChannelMapping(openAICtx, 99, "gpt-5")
  1945. require.True(t, openAIResult.Mapped)
  1946. require.Equal(t, "gpt-5-mini", openAIResult.MappedModel)
  1947. anthropicCtx := WithResolvedTargetPlatform(context.Background(), PlatformAnthropic)
  1948. require.NotNil(t, svc.GetChannelModelPricing(anthropicCtx, 99, "claude-sonnet-4-5"))
  1949. require.Nil(t, svc.GetChannelModelPricing(anthropicCtx, 99, "gpt-5"))
  1950. anthropicResult := svc.ResolveChannelMapping(anthropicCtx, 99, "claude-3-5-sonnet")
  1951. require.True(t, anthropicResult.Mapped)
  1952. require.Equal(t, "claude-sonnet-4-5", anthropicResult.MappedModel)
  1953. }
  1954. // ===========================================================================
  1955. // 9. Antigravity platform isolation — no cross-platform pricing leakage
  1956. // ===========================================================================
  1957. func TestGetChannelModelPricing_AntigravityDoesNotSeeCrossPlatformPricing(t *testing.T) {
  1958. // Channel has anthropic pricing for claude-opus-4-6.
  1959. // Group 10 is antigravity — should NOT see the anthropic pricing.
  1960. ch := Channel{
  1961. ID: 1,
  1962. Status: StatusActive,
  1963. GroupIDs: []int64{10},
  1964. ModelPricing: []ChannelModelPricing{
  1965. {ID: 100, Platform: PlatformAnthropic, Models: []string{"claude-opus-4-6"}, InputPrice: testPtrFloat64(15e-6)},
  1966. },
  1967. }
  1968. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity})
  1969. svc := newTestChannelService(repo)
  1970. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4-6")
  1971. require.Nil(t, result, "antigravity group should NOT see anthropic-platform pricing")
  1972. }
  1973. func TestGetChannelModelPricing_AnthropicCannotSeeAntigravityPricing(t *testing.T) {
  1974. // Channel has antigravity-platform pricing for claude-opus-4-6.
  1975. // Group 10 is anthropic — should NOT see antigravity pricing (no cross-platform leakage).
  1976. ch := Channel{
  1977. ID: 1,
  1978. Status: StatusActive,
  1979. GroupIDs: []int64{10},
  1980. ModelPricing: []ChannelModelPricing{
  1981. {ID: 100, Platform: PlatformAntigravity, Models: []string{"claude-opus-4-6"}, InputPrice: testPtrFloat64(15e-6)},
  1982. },
  1983. }
  1984. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAnthropic})
  1985. svc := newTestChannelService(repo)
  1986. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-opus-4-6")
  1987. require.Nil(t, result, "anthropic group should NOT see antigravity-platform pricing")
  1988. }
  1989. // ===========================================================================
  1990. // 10. Antigravity platform isolation — no cross-platform model mapping
  1991. // ===========================================================================
  1992. func TestResolveChannelMapping_AntigravityDoesNotSeeCrossPlatformMapping(t *testing.T) {
  1993. // Channel has anthropic model mapping: claude-opus-4-5 → claude-opus-4-6.
  1994. // Group 10 is antigravity — should NOT apply the anthropic mapping.
  1995. ch := Channel{
  1996. ID: 1,
  1997. Status: StatusActive,
  1998. GroupIDs: []int64{10},
  1999. ModelMapping: map[string]map[string]string{
  2000. PlatformAnthropic: {
  2001. "claude-opus-4-5": "claude-opus-4-6",
  2002. },
  2003. },
  2004. }
  2005. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity})
  2006. svc := newTestChannelService(repo)
  2007. result := svc.ResolveChannelMapping(context.Background(), 10, "claude-opus-4-5")
  2008. require.False(t, result.Mapped, "antigravity group should NOT apply anthropic mapping")
  2009. require.Equal(t, "claude-opus-4-5", result.MappedModel)
  2010. }
  2011. // ===========================================================================
  2012. // 11. Antigravity platform isolation — same-name model across platforms
  2013. // ===========================================================================
  2014. func TestGetChannelModelPricing_AntigravityDoesNotSeeSameModelFromOtherPlatforms(t *testing.T) {
  2015. // anthropic 和 gemini 都定义了同名模型 "shared-model",价格不同。
  2016. // antigravity 分组不应看到任何一个(各平台严格独立)。
  2017. ch := Channel{
  2018. ID: 1,
  2019. Status: StatusActive,
  2020. GroupIDs: []int64{10},
  2021. ModelPricing: []ChannelModelPricing{
  2022. {ID: 200, Platform: PlatformAnthropic, Models: []string{"shared-model"}, InputPrice: testPtrFloat64(10e-6)},
  2023. {ID: 201, Platform: PlatformGemini, Models: []string{"shared-model"}, InputPrice: testPtrFloat64(5e-6)},
  2024. },
  2025. }
  2026. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity})
  2027. svc := newTestChannelService(repo)
  2028. result := svc.GetChannelModelPricing(context.Background(), 10, "shared-model")
  2029. require.Nil(t, result, "antigravity group should NOT see anthropic/gemini-platform pricing")
  2030. }
  2031. func TestGetChannelModelPricing_AntigravityDoesNotSeeGeminiOnlyPricing(t *testing.T) {
  2032. // 只有 gemini 平台定义了模型 "gemini-model"。
  2033. // antigravity 分组不应看到 gemini 的定价。
  2034. ch := Channel{
  2035. ID: 1,
  2036. Status: StatusActive,
  2037. GroupIDs: []int64{10},
  2038. ModelPricing: []ChannelModelPricing{
  2039. {ID: 300, Platform: PlatformGemini, Models: []string{"gemini-model"}, InputPrice: testPtrFloat64(2e-6)},
  2040. },
  2041. }
  2042. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity})
  2043. svc := newTestChannelService(repo)
  2044. result := svc.GetChannelModelPricing(context.Background(), 10, "gemini-model")
  2045. require.Nil(t, result, "antigravity group should NOT see gemini-platform pricing")
  2046. }
  2047. func TestGetChannelModelPricing_AntigravityDoesNotSeeWildcardFromOtherPlatforms(t *testing.T) {
  2048. // anthropic 和 gemini 都有 "shared-*" 通配符定价。
  2049. // antigravity 分组不应命中任何一个。
  2050. ch := Channel{
  2051. ID: 1,
  2052. Status: StatusActive,
  2053. GroupIDs: []int64{10},
  2054. ModelPricing: []ChannelModelPricing{
  2055. {ID: 400, Platform: PlatformAnthropic, Models: []string{"shared-*"}, InputPrice: testPtrFloat64(10e-6)},
  2056. {ID: 401, Platform: PlatformGemini, Models: []string{"shared-*"}, InputPrice: testPtrFloat64(5e-6)},
  2057. },
  2058. }
  2059. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity})
  2060. svc := newTestChannelService(repo)
  2061. result := svc.GetChannelModelPricing(context.Background(), 10, "shared-model")
  2062. require.Nil(t, result, "antigravity group should NOT see wildcard pricing from other platforms")
  2063. }
  2064. func TestResolveChannelMapping_AntigravityDoesNotSeeMappingFromOtherPlatforms(t *testing.T) {
  2065. // anthropic 和 gemini 都定义了同名模型映射 "alias" → 不同目标。
  2066. // antigravity 分组不应命中任何一个。
  2067. ch := Channel{
  2068. ID: 1,
  2069. Status: StatusActive,
  2070. GroupIDs: []int64{10},
  2071. ModelMapping: map[string]map[string]string{
  2072. PlatformAnthropic: {"alias": "anthropic-target"},
  2073. PlatformGemini: {"alias": "gemini-target"},
  2074. },
  2075. }
  2076. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity})
  2077. svc := newTestChannelService(repo)
  2078. result := svc.ResolveChannelMapping(context.Background(), 10, "alias")
  2079. require.False(t, result.Mapped, "antigravity group should NOT see mapping from other platforms")
  2080. require.Equal(t, "alias", result.MappedModel)
  2081. }
  2082. func TestCheckRestricted_AntigravityDoesNotSeeModelsFromOtherPlatforms(t *testing.T) {
  2083. // anthropic 和 gemini 都定义了同名模型 "shared-model"。
  2084. // antigravity 分组启用了 RestrictModels,"shared-model" 应被限制(各平台独立)。
  2085. ch := Channel{
  2086. ID: 1,
  2087. Status: StatusActive,
  2088. RestrictModels: true,
  2089. GroupIDs: []int64{10},
  2090. ModelPricing: []ChannelModelPricing{
  2091. {ID: 500, Platform: PlatformAnthropic, Models: []string{"shared-model"}, InputPrice: testPtrFloat64(10e-6)},
  2092. {ID: 501, Platform: PlatformGemini, Models: []string{"shared-model"}, InputPrice: testPtrFloat64(5e-6)},
  2093. },
  2094. }
  2095. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity})
  2096. svc := newTestChannelService(repo)
  2097. restricted := svc.IsModelRestricted(context.Background(), 10, "shared-model")
  2098. require.True(t, restricted, "shared-model from other platforms should be restricted for antigravity")
  2099. restricted = svc.IsModelRestricted(context.Background(), 10, "unknown-model")
  2100. require.True(t, restricted, "unknown-model should be restricted for antigravity")
  2101. }
  2102. func TestGetChannelModelPricing_AntigravityOwnPricingWorks(t *testing.T) {
  2103. // antigravity 平台自己配置的定价应正常生效(覆盖 Claude 和 Gemini 模型)。
  2104. ch := Channel{
  2105. ID: 1,
  2106. Status: StatusActive,
  2107. GroupIDs: []int64{10},
  2108. ModelPricing: []ChannelModelPricing{
  2109. {ID: 600, Platform: PlatformAntigravity, Models: []string{"claude-*"}, InputPrice: testPtrFloat64(15e-6)},
  2110. {ID: 601, Platform: PlatformAntigravity, Models: []string{"gemini-*"}, InputPrice: testPtrFloat64(2e-6)},
  2111. },
  2112. }
  2113. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity})
  2114. svc := newTestChannelService(repo)
  2115. // Claude 模型匹配 antigravity 定价
  2116. result := svc.GetChannelModelPricing(context.Background(), 10, "claude-sonnet-4")
  2117. require.NotNil(t, result)
  2118. require.Equal(t, int64(600), result.ID)
  2119. require.InDelta(t, 15e-6, *result.InputPrice, 1e-12)
  2120. // Gemini 模型匹配 antigravity 定价
  2121. result = svc.GetChannelModelPricing(context.Background(), 10, "gemini-2.5-flash")
  2122. require.NotNil(t, result)
  2123. require.Equal(t, int64(601), result.ID)
  2124. require.InDelta(t, 2e-6, *result.InputPrice, 1e-12)
  2125. }
  2126. func TestGetChannelModelPricing_NonAntigravityUnaffected(t *testing.T) {
  2127. // 确保非 antigravity 平台的行为不受影响。
  2128. // anthropic 分组只能看到 anthropic 的定价,看不到 gemini 的。
  2129. ch := Channel{
  2130. ID: 1,
  2131. Status: StatusActive,
  2132. GroupIDs: []int64{10, 20},
  2133. ModelPricing: []ChannelModelPricing{
  2134. {ID: 600, Platform: PlatformAnthropic, Models: []string{"shared-model"}, InputPrice: testPtrFloat64(10e-6)},
  2135. {ID: 601, Platform: PlatformGemini, Models: []string{"shared-model"}, InputPrice: testPtrFloat64(5e-6)},
  2136. },
  2137. }
  2138. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAnthropic, 20: PlatformGemini})
  2139. svc := newTestChannelService(repo)
  2140. // anthropic 分组应该只看到 anthropic 的定价
  2141. result := svc.GetChannelModelPricing(context.Background(), 10, "shared-model")
  2142. require.NotNil(t, result)
  2143. require.Equal(t, int64(600), result.ID)
  2144. require.InDelta(t, 10e-6, *result.InputPrice, 1e-12)
  2145. // gemini 分组应该只看到 gemini 的定价
  2146. result = svc.GetChannelModelPricing(context.Background(), 20, "shared-model")
  2147. require.NotNil(t, result)
  2148. require.Equal(t, int64(601), result.ID)
  2149. require.InDelta(t, 5e-6, *result.InputPrice, 1e-12)
  2150. }
  2151. // ---------------------------------------------------------------------------
  2152. // 10. ToUsageFields
  2153. // ---------------------------------------------------------------------------
  2154. func TestToUsageFields_NoMapping(t *testing.T) {
  2155. r := ChannelMappingResult{
  2156. MappedModel: "claude-opus-4",
  2157. ChannelID: 1,
  2158. Mapped: false,
  2159. BillingModelSource: BillingModelSourceRequested,
  2160. }
  2161. fields := r.ToUsageFields("claude-opus-4", "claude-opus-4")
  2162. require.Equal(t, int64(1), fields.ChannelID)
  2163. require.Equal(t, "claude-opus-4", fields.OriginalModel)
  2164. require.Equal(t, "claude-opus-4", fields.ChannelMappedModel)
  2165. require.Equal(t, BillingModelSourceRequested, fields.BillingModelSource)
  2166. require.Empty(t, fields.ModelMappingChain)
  2167. }
  2168. func TestToUsageFields_WithChannelMapping(t *testing.T) {
  2169. r := ChannelMappingResult{
  2170. MappedModel: "claude-sonnet-4-20250514",
  2171. ChannelID: 2,
  2172. Mapped: true,
  2173. BillingModelSource: BillingModelSourceChannelMapped,
  2174. }
  2175. fields := r.ToUsageFields("claude-sonnet-4", "claude-sonnet-4-20250514")
  2176. require.Equal(t, int64(2), fields.ChannelID)
  2177. require.Equal(t, "claude-sonnet-4", fields.OriginalModel)
  2178. require.Equal(t, "claude-sonnet-4-20250514", fields.ChannelMappedModel)
  2179. require.Equal(t, "claude-sonnet-4→claude-sonnet-4-20250514", fields.ModelMappingChain)
  2180. }
  2181. func TestToUsageFields_WithUpstreamDifference(t *testing.T) {
  2182. r := ChannelMappingResult{
  2183. MappedModel: "claude-sonnet-4",
  2184. ChannelID: 3,
  2185. Mapped: true,
  2186. BillingModelSource: BillingModelSourceUpstream,
  2187. }
  2188. fields := r.ToUsageFields("my-alias", "claude-sonnet-4-20250514")
  2189. require.Equal(t, "my-alias", fields.OriginalModel)
  2190. require.Equal(t, "claude-sonnet-4", fields.ChannelMappedModel)
  2191. require.Equal(t, "my-alias→claude-sonnet-4→claude-sonnet-4-20250514", fields.ModelMappingChain)
  2192. }
  2193. // ---------------------------------------------------------------------------
  2194. // 11. validatePricingBillingMode (moved from handler tests)
  2195. // ---------------------------------------------------------------------------
  2196. func TestValidatePricingBillingMode(t *testing.T) {
  2197. tests := []struct {
  2198. name string
  2199. pricing []ChannelModelPricing
  2200. wantErr bool
  2201. errMsg string
  2202. }{
  2203. {
  2204. name: "token mode - valid",
  2205. pricing: []ChannelModelPricing{{BillingMode: BillingModeToken}},
  2206. },
  2207. {
  2208. name: "per_request with price - valid",
  2209. pricing: []ChannelModelPricing{{
  2210. BillingMode: BillingModePerRequest,
  2211. PerRequestPrice: testPtrFloat64(0.5),
  2212. }},
  2213. },
  2214. {
  2215. name: "per_request with intervals - valid",
  2216. pricing: []ChannelModelPricing{{
  2217. BillingMode: BillingModePerRequest,
  2218. Intervals: []PricingInterval{{MinTokens: 0, MaxTokens: testPtrInt(1000), PerRequestPrice: testPtrFloat64(0.1)}},
  2219. }},
  2220. },
  2221. {
  2222. name: "per_request no price no intervals - invalid",
  2223. pricing: []ChannelModelPricing{{BillingMode: BillingModePerRequest}},
  2224. wantErr: true,
  2225. errMsg: "per-request price or intervals required",
  2226. },
  2227. {
  2228. name: "image no price no intervals - invalid",
  2229. pricing: []ChannelModelPricing{{BillingMode: BillingModeImage}},
  2230. wantErr: true,
  2231. errMsg: "per-request price or intervals required",
  2232. },
  2233. {
  2234. name: "empty list - valid",
  2235. pricing: []ChannelModelPricing{},
  2236. },
  2237. {
  2238. name: "negative input_price - invalid",
  2239. pricing: []ChannelModelPricing{{
  2240. BillingMode: BillingModeToken,
  2241. InputPrice: testPtrFloat64(-0.01),
  2242. }},
  2243. wantErr: true,
  2244. errMsg: "input_price must be >= 0",
  2245. },
  2246. {
  2247. name: "interval with no price fields - invalid",
  2248. pricing: []ChannelModelPricing{{
  2249. BillingMode: BillingModePerRequest,
  2250. PerRequestPrice: testPtrFloat64(0.5),
  2251. Intervals: []PricingInterval{{MinTokens: 0, MaxTokens: testPtrInt(1000)}},
  2252. }},
  2253. wantErr: true,
  2254. errMsg: "has no price fields set",
  2255. },
  2256. }
  2257. for _, tt := range tests {
  2258. t.Run(tt.name, func(t *testing.T) {
  2259. err := validatePricingBillingMode(tt.pricing)
  2260. if tt.wantErr {
  2261. require.Error(t, err)
  2262. require.Contains(t, err.Error(), tt.errMsg)
  2263. } else {
  2264. require.NoError(t, err)
  2265. }
  2266. })
  2267. }
  2268. }
  2269. func validTimePricingForTest() *ChannelTimePricing {
  2270. return &ChannelTimePricing{Timezone: "Asia/Shanghai", Periods: []ChannelTimePricingPeriod{
  2271. {StartTime: "09:00", EndTime: "12:00", Multiplier: 2},
  2272. }}
  2273. }
  2274. func TestValidatePricingTimePricing(t *testing.T) {
  2275. token := []ChannelModelPricing{{BillingMode: BillingModeToken, TimePricing: validTimePricingForTest()}}
  2276. require.NoError(t, validatePricingTimePricing(token))
  2277. implicitToken := []ChannelModelPricing{{TimePricing: validTimePricingForTest()}}
  2278. require.NoError(t, validatePricingTimePricing(implicitToken))
  2279. image := []ChannelModelPricing{{BillingMode: BillingModeImage, TimePricing: validTimePricingForTest()}}
  2280. modeErr := infraerrors.FromError(validatePricingTimePricing(image))
  2281. require.Equal(t, int32(http.StatusBadRequest), modeErr.Code)
  2282. require.Equal(t, "TIME_PRICING_UNSUPPORTED_MODE", modeErr.Reason)
  2283. invalid := []ChannelModelPricing{{
  2284. Platform: PlatformOpenAI,
  2285. Models: []string{"gpt-5"},
  2286. BillingMode: BillingModeToken,
  2287. TimePricing: &ChannelTimePricing{Timezone: "UTC+8", Periods: validTimePricingForTest().Periods},
  2288. }}
  2289. invalidErr := infraerrors.FromError(validatePricingTimePricing(invalid))
  2290. require.Equal(t, int32(http.StatusBadRequest), invalidErr.Code)
  2291. require.Equal(t, "INVALID_TIME_PRICING", invalidErr.Reason)
  2292. require.Contains(t, invalidErr.Message, "platform 'openai'")
  2293. require.Contains(t, invalidErr.Message, "models [gpt-5]")
  2294. invalidMultiplier := []ChannelModelPricing{{
  2295. Platform: PlatformOpenAI,
  2296. Models: []string{"gpt-5"},
  2297. BillingMode: BillingModeToken,
  2298. TimePricing: &ChannelTimePricing{Timezone: "Asia/Shanghai", Periods: []ChannelTimePricingPeriod{{
  2299. StartTime: "09:00", EndTime: "12:00", Multiplier: 1e-12,
  2300. }}},
  2301. }}
  2302. invalidMultiplierRawErr := validatePricingTimePricing(invalidMultiplier)
  2303. require.Error(t, invalidMultiplierRawErr)
  2304. invalidMultiplierErr := infraerrors.FromError(invalidMultiplierRawErr)
  2305. require.Equal(t, int32(http.StatusBadRequest), invalidMultiplierErr.Code)
  2306. require.Equal(t, "INVALID_TIME_PRICING", invalidMultiplierErr.Reason)
  2307. empty := []ChannelModelPricing{{BillingMode: BillingModeToken, TimePricing: &ChannelTimePricing{Timezone: "Asia/Shanghai"}}}
  2308. require.NoError(t, validatePricingTimePricing(empty))
  2309. require.Nil(t, empty[0].TimePricing)
  2310. }
  2311. func TestValidateAccountStatsPricingRulesRejectsTimePricing(t *testing.T) {
  2312. rules := []AccountStatsPricingRule{{Pricing: []ChannelModelPricing{{
  2313. BillingMode: BillingModeToken,
  2314. TimePricing: validTimePricingForTest(),
  2315. }}}}
  2316. appErr := infraerrors.FromError(validateAccountStatsPricingRules(rules))
  2317. require.Equal(t, int32(http.StatusBadRequest), appErr.Code)
  2318. require.Equal(t, "ACCOUNT_STATS_TIME_PRICING_UNSUPPORTED", appErr.Reason)
  2319. }
  2320. // ---------------------------------------------------------------------------
  2321. // 12. Antigravity wildcard mapping isolation
  2322. // ---------------------------------------------------------------------------
  2323. func TestResolveChannelMapping_AntigravityDoesNotSeeWildcardMappingFromOtherPlatforms(t *testing.T) {
  2324. ch := Channel{
  2325. ID: 1,
  2326. Status: StatusActive,
  2327. GroupIDs: []int64{10, 20},
  2328. ModelMapping: map[string]map[string]string{
  2329. PlatformAnthropic: {"claude-*": "claude-override"},
  2330. PlatformGemini: {"gemini-*": "gemini-override"},
  2331. },
  2332. }
  2333. repo := makeStandardRepo(ch, map[int64]string{10: PlatformAntigravity, 20: PlatformAnthropic})
  2334. svc := newTestChannelService(repo)
  2335. // antigravity 分组不应看到 anthropic/gemini 的通配符映射
  2336. result := svc.ResolveChannelMapping(context.Background(), 10, "claude-opus-4")
  2337. require.False(t, result.Mapped)
  2338. require.Equal(t, "claude-opus-4", result.MappedModel)
  2339. result = svc.ResolveChannelMapping(context.Background(), 10, "gemini-2.5-pro")
  2340. require.False(t, result.Mapped)
  2341. require.Equal(t, "gemini-2.5-pro", result.MappedModel)
  2342. // anthropic 分组应该能看到 anthropic 的通配符映射
  2343. result = svc.ResolveChannelMapping(context.Background(), 20, "claude-opus-4")
  2344. require.True(t, result.Mapped)
  2345. require.Equal(t, "claude-override", result.MappedModel)
  2346. }
  2347. // ---------------------------------------------------------------------------
  2348. // 13. Create/Update with mapping conflict validation
  2349. // ---------------------------------------------------------------------------
  2350. func TestCreate_MappingConflict(t *testing.T) {
  2351. repo := &mockChannelRepository{}
  2352. svc := newTestChannelService(repo)
  2353. _, err := svc.Create(context.Background(), &CreateChannelInput{
  2354. Name: "test",
  2355. ModelMapping: map[string]map[string]string{
  2356. PlatformAnthropic: {
  2357. "claude-*": "target-a",
  2358. "claude-opus-*": "target-b",
  2359. },
  2360. },
  2361. })
  2362. require.Error(t, err)
  2363. require.Contains(t, err.Error(), "MAPPING_PATTERN_CONFLICT")
  2364. }
  2365. func TestUpdate_MappingConflict(t *testing.T) {
  2366. existingChannel := &Channel{
  2367. ID: 1,
  2368. Name: "existing",
  2369. Status: StatusActive,
  2370. }
  2371. repo := &mockChannelRepository{
  2372. getByIDFn: func(_ context.Context, _ int64) (*Channel, error) {
  2373. return existingChannel, nil
  2374. },
  2375. }
  2376. svc := newTestChannelService(repo)
  2377. conflictMapping := map[string]map[string]string{
  2378. PlatformAnthropic: {
  2379. "claude-*": "target-a",
  2380. "claude-opus-*": "target-b",
  2381. },
  2382. }
  2383. _, err := svc.Update(context.Background(), 1, &UpdateChannelInput{
  2384. ModelMapping: conflictMapping,
  2385. })
  2386. require.Error(t, err)
  2387. require.Contains(t, err.Error(), "MAPPING_PATTERN_CONFLICT")
  2388. }