Compare commits
25 Commits
4eebdfb8db
...
v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
| 6de7a2d2e1 | |||
| 6181923d8d | |||
| 235efb0e62 | |||
| 6b1af27ea2 | |||
| 32f48777f3 | |||
| bc7a7c6e81 | |||
| 3cd0458c2c | |||
| 8eea30ea11 | |||
| 9e33e570af | |||
| 7653385838 | |||
| 2c401f7ae6 | |||
| a9972360c2 | |||
| b00fa4dcee | |||
| 92525b39c3 | |||
| 38a2555c7b | |||
| 9622d44aac | |||
| 155244433f | |||
| 2c043c6cf7 | |||
| f5c82b6980 | |||
| 9105a36097 | |||
| f1ee646ca4 | |||
| b9b487c591 | |||
| 4c62c071fb | |||
| b2e9dd8b7f | |||
| d143c5f3df |
7
.editorconfig
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
end_of_line = lf
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
|
charset = utf-8
|
||||||
9
.gitattributes
vendored
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
assets/*.png filter=lfs diff=lfs merge=lfs -text
|
||||||
|
assets/**/*.png filter=lfs diff=lfs merge=lfs -text
|
||||||
|
assets/*.icns filter=lfs diff=lfs merge=lfs -text
|
||||||
|
assets/**/*.icns filter=lfs diff=lfs merge=lfs -text
|
||||||
|
assets/*.ico filter=lfs diff=lfs merge=lfs -text
|
||||||
|
assets/**/*.ico filter=lfs diff=lfs merge=lfs -text
|
||||||
|
frontend/public/*.png filter=lfs diff=lfs merge=lfs -text
|
||||||
|
frontend/public/**/*.png filter=lfs diff=lfs merge=lfs -text
|
||||||
221
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*.*.*'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
prepare:
|
||||||
|
name: Prepare Release
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
outputs:
|
||||||
|
version: ${{ steps.version.outputs.version }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
lfs: true
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version-file: go.work
|
||||||
|
cache-dependency-path: |
|
||||||
|
backend/go.sum
|
||||||
|
versionctl/go.sum
|
||||||
|
|
||||||
|
- name: Verify tag and VERSION
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
version=$(go run ./versionctl print)
|
||||||
|
go run ./versionctl verify-tag "${GITHUB_REF_NAME}"
|
||||||
|
printf 'version=%s\n' "$version" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
build-linux:
|
||||||
|
name: Build Linux Assets
|
||||||
|
needs: prepare
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
lfs: true
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version-file: go.work
|
||||||
|
cache-dependency-path: |
|
||||||
|
backend/go.sum
|
||||||
|
versionctl/go.sum
|
||||||
|
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: oven-sh/setup-bun@v2
|
||||||
|
|
||||||
|
- name: Install Linux desktop build dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y libayatana-appindicator3-dev libgtk-3-dev
|
||||||
|
|
||||||
|
- name: Preflight Linux release toolchain
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
command -v go
|
||||||
|
go version
|
||||||
|
command -v bun
|
||||||
|
bun --version
|
||||||
|
command -v gcc
|
||||||
|
gcc --version
|
||||||
|
command -v pkg-config
|
||||||
|
pkg-config --modversion ayatana-appindicator3-0.1
|
||||||
|
pkg-config --modversion gtk+-3.0
|
||||||
|
make release-assets-check
|
||||||
|
|
||||||
|
- name: Build Linux release assets
|
||||||
|
run: make release-assets-linux
|
||||||
|
|
||||||
|
- name: Upload Linux release assets
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: release-linux
|
||||||
|
path: build/release/*
|
||||||
|
|
||||||
|
build-windows:
|
||||||
|
name: Build Windows Assets
|
||||||
|
needs: prepare
|
||||||
|
runs-on: windows-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
lfs: true
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version-file: go.work
|
||||||
|
cache-dependency-path: |
|
||||||
|
backend/go.sum
|
||||||
|
versionctl/go.sum
|
||||||
|
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: oven-sh/setup-bun@v2
|
||||||
|
|
||||||
|
- name: Setup MSYS2 toolchain
|
||||||
|
uses: msys2/setup-msys2@v2
|
||||||
|
with:
|
||||||
|
msystem: MINGW64
|
||||||
|
path-type: inherit
|
||||||
|
update: true
|
||||||
|
install: >-
|
||||||
|
make
|
||||||
|
mingw-w64-x86_64-gcc
|
||||||
|
|
||||||
|
- name: Preflight Windows release toolchain
|
||||||
|
shell: msys2 {0}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
command -v go
|
||||||
|
go version
|
||||||
|
command -v bun
|
||||||
|
bun --version
|
||||||
|
command -v make
|
||||||
|
make --version
|
||||||
|
command -v gcc
|
||||||
|
gcc --version
|
||||||
|
command -v windres
|
||||||
|
windres --version
|
||||||
|
if command -v powershell.exe >/dev/null 2>&1; then
|
||||||
|
powershell.exe -NoProfile -Command '$PSVersionTable.PSVersion.ToString()'
|
||||||
|
else
|
||||||
|
command -v powershell
|
||||||
|
powershell -NoProfile -Command '$PSVersionTable.PSVersion.ToString()'
|
||||||
|
fi
|
||||||
|
make release-assets-check
|
||||||
|
|
||||||
|
- name: Build Windows release assets
|
||||||
|
shell: msys2 {0}
|
||||||
|
run: make release-assets-windows
|
||||||
|
|
||||||
|
- name: Upload Windows release assets
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: release-windows
|
||||||
|
path: build/release/*
|
||||||
|
|
||||||
|
build-macos:
|
||||||
|
name: Build macOS Assets
|
||||||
|
needs: prepare
|
||||||
|
runs-on: macos-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
lfs: true
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version-file: go.work
|
||||||
|
cache-dependency-path: |
|
||||||
|
backend/go.sum
|
||||||
|
versionctl/go.sum
|
||||||
|
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: oven-sh/setup-bun@v2
|
||||||
|
|
||||||
|
- name: Preflight macOS release toolchain
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
command -v go
|
||||||
|
go version
|
||||||
|
command -v bun
|
||||||
|
bun --version
|
||||||
|
command -v ditto
|
||||||
|
xcrun --find lipo
|
||||||
|
xcrun --find vtool
|
||||||
|
make release-assets-check
|
||||||
|
|
||||||
|
- name: Build macOS release assets
|
||||||
|
run: make release-assets-macos
|
||||||
|
|
||||||
|
- name: Upload macOS release assets
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: release-macos
|
||||||
|
path: build/release/*
|
||||||
|
|
||||||
|
draft-release:
|
||||||
|
name: Create Draft Release
|
||||||
|
needs: [prepare, build-linux, build-windows, build-macos]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
steps:
|
||||||
|
- name: Download release assets
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
pattern: release-*
|
||||||
|
merge-multiple: true
|
||||||
|
path: dist
|
||||||
|
|
||||||
|
- name: Publish draft release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
name: v${{ needs.prepare.outputs.version }}
|
||||||
|
tag_name: ${{ github.ref_name }}
|
||||||
|
draft: true
|
||||||
|
files: |
|
||||||
|
dist/*
|
||||||
2
.gitignore
vendored
@@ -408,7 +408,9 @@ temp
|
|||||||
skills-lock.json
|
skills-lock.json
|
||||||
.worktrees
|
.worktrees
|
||||||
!scripts/build/
|
!scripts/build/
|
||||||
|
backend/bin
|
||||||
|
|
||||||
# Embedfs generated
|
# Embedfs generated
|
||||||
embedfs/assets/
|
embedfs/assets/
|
||||||
embedfs/frontend-dist/
|
embedfs/frontend-dist/
|
||||||
|
backend/cmd/desktop/rsrc_windows_*.syso
|
||||||
|
|||||||
3
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"files.eol": "\n"
|
||||||
|
}
|
||||||
184
LICENSE
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction, and
|
||||||
|
distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
||||||
|
owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all other entities
|
||||||
|
that control, are controlled by, or are under common control with that entity.
|
||||||
|
For the purposes of this definition, "control" means (i) the power, direct or
|
||||||
|
indirect, to cause the direction or management of such entity, whether by
|
||||||
|
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
||||||
|
permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications, including
|
||||||
|
but not limited to software source code, documentation source, and configuration
|
||||||
|
files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical transformation or
|
||||||
|
translation of a Source form, including but not limited to compiled object code,
|
||||||
|
generated documentation, and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or Object form,
|
||||||
|
made available under the License, as indicated by a copyright notice that is
|
||||||
|
included in or attached to the work (an example is provided in the Appendix
|
||||||
|
below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
||||||
|
is based on (or derived from) the Work and for which the editorial revisions,
|
||||||
|
annotations, elaborations, or other modifications represent, as a whole, an
|
||||||
|
original work of authorship. For the purposes of this License, Derivative Works
|
||||||
|
shall not include works that remain separable from, or merely link (or bind by
|
||||||
|
name) to the interfaces of, the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including the original version
|
||||||
|
of the Work and any modifications or additions to that Work or Derivative Works
|
||||||
|
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
||||||
|
by the copyright owner or by an individual or Legal Entity authorized to submit
|
||||||
|
on behalf of the copyright owner. For the purposes of this definition,
|
||||||
|
"submitted" means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems, and
|
||||||
|
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
||||||
|
the purpose of discussing and improving the Work, but excluding communication
|
||||||
|
that is conspicuously marked or otherwise designated in writing by the copyright
|
||||||
|
owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
||||||
|
of whom a Contribution has been received by Licensor and subsequently
|
||||||
|
incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of this
|
||||||
|
License, each Contributor hereby grants to You a perpetual, worldwide,
|
||||||
|
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
|
||||||
|
reproduce, prepare Derivative Works of, publicly display, publicly perform,
|
||||||
|
sublicense, and distribute the Work and such Derivative Works in Source or
|
||||||
|
Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of this License,
|
||||||
|
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
|
||||||
|
no-charge, royalty-free, irrevocable (except as stated in this section) patent
|
||||||
|
license to make, have made, use, offer to sell, sell, import, and otherwise
|
||||||
|
transfer the Work, where such license applies only to those patent claims
|
||||||
|
licensable by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s) with the Work
|
||||||
|
to which such Contribution(s) was submitted. If You institute patent litigation
|
||||||
|
against any entity (including a cross-claim or counterclaim in a lawsuit)
|
||||||
|
alleging that the Work or a Contribution incorporated within the Work
|
||||||
|
constitutes direct or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate as of the date
|
||||||
|
such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the Work or
|
||||||
|
Derivative Works thereof in any medium, with or without modifications, and in
|
||||||
|
Source or Object form, provided that You meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or Derivative Works a copy of
|
||||||
|
this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices stating that
|
||||||
|
You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works that You
|
||||||
|
distribute, all copyright, patent, trademark, and attribution notices from the
|
||||||
|
Source form of the Work, excluding those notices that do not pertain to any part
|
||||||
|
of the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its distribution, then
|
||||||
|
any Derivative Works that You distribute must include a readable copy of the
|
||||||
|
attribution notices contained within such NOTICE file, excluding those notices
|
||||||
|
that do not pertain to any part of the Derivative Works, in at least one of the
|
||||||
|
following places: within a NOTICE text file distributed as part of the
|
||||||
|
Derivative Works; within the Source form or documentation, if provided along
|
||||||
|
with the Derivative Works; or, within a display generated by the Derivative
|
||||||
|
Works, if and wherever such third-party notices normally appear. The contents of
|
||||||
|
the NOTICE file are for informational purposes only and do not modify the
|
||||||
|
License. You may add Your own attribution notices within Derivative Works that
|
||||||
|
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
||||||
|
provided that such additional attribution notices cannot be construed as
|
||||||
|
modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and may provide
|
||||||
|
additional or different license terms and conditions for use, reproduction, or
|
||||||
|
distribution of Your modifications, or for any such Derivative Works as a whole,
|
||||||
|
provided Your use, reproduction, and distribution of the Work otherwise complies
|
||||||
|
with the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise, any
|
||||||
|
Contribution intentionally submitted for inclusion in the Work by You to the
|
||||||
|
Licensor shall be under the terms and conditions of this License, without any
|
||||||
|
additional terms or conditions. Notwithstanding the above, nothing herein shall
|
||||||
|
supersede or modify the terms of any separate license agreement you may have
|
||||||
|
executed with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade names,
|
||||||
|
trademarks, service marks, or product names of the Licensor, except as required
|
||||||
|
for reasonable and customary use in describing the origin of the Work and
|
||||||
|
reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
|
||||||
|
writing, Licensor provides the Work (and each Contributor provides its
|
||||||
|
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
KIND, either express or implied, including, without limitation, any warranties
|
||||||
|
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any risks
|
||||||
|
associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory, whether in
|
||||||
|
tort (including negligence), contract, or otherwise, unless required by
|
||||||
|
applicable law (such as deliberate and grossly negligent acts) or agreed to in
|
||||||
|
writing, shall any Contributor be liable to You for damages, including any
|
||||||
|
direct, indirect, special, incidental, or consequential damages of any character
|
||||||
|
arising as a result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill, work stoppage,
|
||||||
|
computer failure or malfunction, or any and all other commercial damages or
|
||||||
|
losses), even if such Contributor has been advised of the possibility of such
|
||||||
|
damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing the Work or
|
||||||
|
Derivative Works thereof, You may choose to offer, and charge a fee for,
|
||||||
|
acceptance of support, warranty, indemnity, or other liability obligations
|
||||||
|
and/or rights consistent with this License. However, in accepting such
|
||||||
|
obligations, You may act only on Your own behalf and on Your sole
|
||||||
|
responsibility, not on behalf of any other Contributor, and only if You agree to
|
||||||
|
indemnify, defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason of your
|
||||||
|
accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following boilerplate
|
||||||
|
notice, with the fields enclosed by brackets "[]" replaced with your own
|
||||||
|
identifying information. (Don't include the brackets!) The text should be
|
||||||
|
enclosed in the appropriate comment syntax for the file format. We also
|
||||||
|
recommend that a file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier identification within
|
||||||
|
third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
393
Makefile
@@ -1,208 +1,255 @@
|
|||||||
.PHONY: all dev build test lint clean \
|
.PHONY: \
|
||||||
backend-build backend-run backend-dev backend-test backend-test-all backend-test-unit backend-test-integration backend-test-coverage \
|
lint test clean \
|
||||||
backend-lint backend-clean backend-deps backend-generate \
|
version-sync version-check version-bump \
|
||||||
backend-db-up backend-db-down backend-db-status backend-db-create \
|
server-run server-build server-lint server-test server-clean \
|
||||||
test-mysql-up test-mysql-down test-mysql test-mysql-quick \
|
desktop-build-mac desktop-build-win desktop-build-linux \
|
||||||
frontend-build frontend-dev frontend-test frontend-test-watch frontend-test-coverage frontend-test-e2e frontend-lint frontend-clean \
|
desktop-lint desktop-test desktop-clean \
|
||||||
desktop-build desktop-build-mac desktop-build-win desktop-build-linux \
|
release-assets-check release-assets-linux release-assets-windows release-assets-macos \
|
||||||
desktop-dev desktop-test desktop-package-mac desktop-package-win desktop-package-linux desktop-clean \
|
_backend-lint _backend-test _backend-clean _backend-build \
|
||||||
desktop-prepare-frontend desktop-prepare-embedfs
|
_versionctl-lint _versionctl-test \
|
||||||
|
_frontend-install _frontend-build _frontend-check _frontend-test _frontend-dev _frontend-clean \
|
||||||
|
_desktop-test _desktop-clean _desktop-prepare-frontend _desktop-prepare-embedfs _desktop-prepare-windows-resource \
|
||||||
|
_server-run-backend _server-run-frontend
|
||||||
|
|
||||||
|
# Delay shell lookups until a target needs them, then cache the result for this make run.
|
||||||
|
lazy_shell = $(or $($(1)),$(eval $(1) := $(shell $(2)))$($(1)))
|
||||||
|
|
||||||
|
VERSION = $(call lazy_shell,_VERSION,go run ./versionctl print)
|
||||||
|
GIT_COMMIT ?= $(call lazy_shell,_GIT_COMMIT,git rev-parse --short HEAD 2>/dev/null || printf 'unknown')
|
||||||
|
BUILD_TIME ?= $(call lazy_shell,_BUILD_TIME,date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
GO_LDFLAGS = -X nex/backend/pkg/buildinfo.version=$(VERSION) -X nex/backend/pkg/buildinfo.commit=$(GIT_COMMIT) -X nex/backend/pkg/buildinfo.buildTime=$(BUILD_TIME)
|
||||||
|
GO_LDFLAGS_WIN = $(GO_LDFLAGS) -H=windowsgui
|
||||||
|
RELEASE_DIR := build/release
|
||||||
|
SERVER_LINUX_ASSET = $(call lazy_shell,_SERVER_LINUX_ASSET,go run ./versionctl asset-name server linux amd64)
|
||||||
|
SERVER_WINDOWS_ASSET = $(call lazy_shell,_SERVER_WINDOWS_ASSET,go run ./versionctl asset-name server windows amd64)
|
||||||
|
SERVER_DARWIN_AMD64_ASSET = $(call lazy_shell,_SERVER_DARWIN_AMD64_ASSET,go run ./versionctl asset-name server darwin amd64)
|
||||||
|
SERVER_DARWIN_ARM64_ASSET = $(call lazy_shell,_SERVER_DARWIN_ARM64_ASSET,go run ./versionctl asset-name server darwin arm64)
|
||||||
|
DESKTOP_LINUX_ASSET = $(call lazy_shell,_DESKTOP_LINUX_ASSET,go run ./versionctl asset-name desktop linux)
|
||||||
|
DESKTOP_WINDOWS_ASSET = $(call lazy_shell,_DESKTOP_WINDOWS_ASSET,go run ./versionctl asset-name desktop windows)
|
||||||
|
DESKTOP_MACOS_ASSET = $(call lazy_shell,_DESKTOP_MACOS_ASSET,go run ./versionctl asset-name desktop macos)
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# 顶层便捷命令
|
# 全局命令
|
||||||
# ============================================
|
# ============================================
|
||||||
|
|
||||||
dev:
|
lint: _backend-lint _frontend-check _versionctl-lint
|
||||||
@echo "🚀 Starting development environment..."
|
@printf 'Lint complete\n'
|
||||||
@$(MAKE) -j2 backend-dev frontend-dev
|
|
||||||
|
|
||||||
build: backend-build frontend-build
|
test: _backend-test _frontend-test _desktop-test _versionctl-test
|
||||||
@echo "✅ Build complete"
|
@printf 'All tests passed\n'
|
||||||
|
|
||||||
test: backend-test desktop-test frontend-test
|
clean: _backend-clean _frontend-clean _desktop-clean
|
||||||
@echo "✅ All tests passed"
|
@printf 'Clean complete\n'
|
||||||
|
|
||||||
lint: backend-lint frontend-lint
|
|
||||||
@echo "✅ Lint complete"
|
|
||||||
|
|
||||||
all: build test lint
|
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# 后端
|
# 版本管理
|
||||||
# ============================================
|
# ============================================
|
||||||
|
|
||||||
backend-build:
|
version-sync:
|
||||||
cd backend && go build -o bin/server ./cmd/server
|
go run ./versionctl sync
|
||||||
|
|
||||||
backend-run:
|
version-check:
|
||||||
cd backend && go run ./cmd/server
|
go run ./versionctl check
|
||||||
|
|
||||||
backend-dev:
|
version-bump: BUMP ?= patch
|
||||||
cd backend && go run ./cmd/server
|
version-bump:
|
||||||
|
$(eval _BUMP_ARG := $(if $(SET_VERSION),$(SET_VERSION),$(BUMP)))
|
||||||
backend-test:
|
$(eval _NEW_VERSION := $(shell go run ./versionctl bump $(_BUMP_ARG)))
|
||||||
cd backend && go test ./internal/... ./pkg/... ./tests/... ./cmd/server/... -v
|
git add VERSION frontend/
|
||||||
|
git commit -m "chore: 版本升迁 v$(_NEW_VERSION)"
|
||||||
backend-test-all:
|
git tag "v$(_NEW_VERSION)"
|
||||||
cd backend && go test ./... -v
|
@printf '版本升迁完成: v%s\n' "$(_NEW_VERSION)"
|
||||||
|
|
||||||
backend-test-unit:
|
|
||||||
cd backend && go test ./internal/... ./pkg/... -v
|
|
||||||
|
|
||||||
backend-test-integration:
|
|
||||||
cd backend && go test ./tests/... -v
|
|
||||||
|
|
||||||
backend-test-coverage:
|
|
||||||
cd backend && go test ./... -coverprofile=coverage.out
|
|
||||||
cd backend && go tool cover -html=coverage.out -o coverage.html
|
|
||||||
@echo "Coverage report generated: backend/coverage.html"
|
|
||||||
|
|
||||||
backend-lint:
|
|
||||||
cd backend && go tool golangci-lint run ./...
|
|
||||||
|
|
||||||
backend-clean:
|
|
||||||
rm -rf backend/bin/ backend/coverage.out backend/coverage.html
|
|
||||||
|
|
||||||
backend-deps:
|
|
||||||
cd backend && go mod tidy
|
|
||||||
|
|
||||||
backend-generate:
|
|
||||||
cd backend && go generate ./...
|
|
||||||
|
|
||||||
backend-db-up:
|
|
||||||
@echo "Running database migration up..."
|
|
||||||
cd backend && goose -dir migrations/sqlite sqlite3 "$(DB_PATH)" up
|
|
||||||
|
|
||||||
backend-db-down:
|
|
||||||
@echo "Running database migration down..."
|
|
||||||
cd backend && goose -dir migrations/sqlite sqlite3 "$(DB_PATH)" down
|
|
||||||
|
|
||||||
backend-db-status:
|
|
||||||
@echo "Checking database migration status..."
|
|
||||||
cd backend && goose -dir migrations/sqlite sqlite3 "$(DB_PATH)" status
|
|
||||||
|
|
||||||
backend-db-create:
|
|
||||||
@read -p "Migration name: " name; \
|
|
||||||
cd backend && goose -dir migrations/sqlite create $$name sql; \
|
|
||||||
cd backend && goose -dir migrations/mysql create $$name sql
|
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# MySQL 专项测试
|
# Server 模式
|
||||||
# ============================================
|
# ============================================
|
||||||
|
|
||||||
test-mysql-up:
|
server-run:
|
||||||
@echo "Starting MySQL test container..."
|
@$(MAKE) -j2 _server-run-backend _server-run-frontend
|
||||||
cd backend/tests/mysql && docker-compose up -d
|
|
||||||
@echo "Waiting for MySQL to be ready..."
|
server-build: version-check _backend-build _frontend-build
|
||||||
@for i in $$(seq 1 30); do \
|
@printf 'Server build complete\n'
|
||||||
if docker exec nex-mysql-test mysqladmin ping -h localhost -u root -ptestpass --silent 2>/dev/null; then \
|
|
||||||
echo "MySQL is ready!"; \
|
server-lint: _backend-lint _frontend-check
|
||||||
exit 0; \
|
@printf 'Server lint complete\n'
|
||||||
|
|
||||||
|
server-test: _backend-test _frontend-test
|
||||||
|
@printf 'Server tests passed\n'
|
||||||
|
|
||||||
|
server-clean: _backend-clean _frontend-clean
|
||||||
|
@printf 'Server artifacts cleaned\n'
|
||||||
|
|
||||||
|
_server-run-backend:
|
||||||
|
@$(MAKE) -C backend run
|
||||||
|
|
||||||
|
_server-run-frontend: _frontend-install
|
||||||
|
cd frontend && bun run dev
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# Desktop 模式
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
desktop-build-mac: version-check _desktop-prepare-frontend _desktop-prepare-embedfs
|
||||||
|
@printf 'Building macOS desktop...\n'
|
||||||
|
cd backend && CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -ldflags "$(GO_LDFLAGS)" -o ../build/nex-mac-arm64 ./cmd/desktop
|
||||||
|
cd backend && CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -ldflags "$(GO_LDFLAGS)" -o ../build/nex-mac-amd64 ./cmd/desktop
|
||||||
|
lipo -create build/nex-mac-arm64 build/nex-mac-amd64 -output build/nex-mac-universal
|
||||||
|
@printf 'Packaging macOS app bundle...\n'
|
||||||
|
mkdir -p build/Nex.app/Contents/MacOS build/Nex.app/Contents/Resources
|
||||||
|
cp build/nex-mac-universal build/Nex.app/Contents/MacOS/nex
|
||||||
|
@if [ -f assets/icon.icns ]; then \
|
||||||
|
cp assets/icon.icns build/Nex.app/Contents/Resources/; \
|
||||||
|
else \
|
||||||
|
printf 'Missing assets/icon.icns\n'; \
|
||||||
|
fi
|
||||||
|
@MIN_MACOS_VERSION=$$(vtool -show-build build/nex-mac-universal | awk '/minos / {print $$2; exit}'); \
|
||||||
|
if [ -z "$$MIN_MACOS_VERSION" ]; then \
|
||||||
|
printf 'Unable to read macOS minimum version\n'; \
|
||||||
|
exit 1; \
|
||||||
fi; \
|
fi; \
|
||||||
echo "Waiting... ($$i/30)"; \
|
go run ./versionctl macos-plist "$$MIN_MACOS_VERSION" > build/Nex.app/Contents/Info.plist
|
||||||
sleep 1; \
|
chmod +x build/Nex.app/Contents/MacOS/nex
|
||||||
done; \
|
@printf 'macOS desktop build complete\n'
|
||||||
echo "MySQL failed to start"; \
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
test-mysql-down:
|
desktop-build-win: version-check _desktop-prepare-frontend _desktop-prepare-embedfs _desktop-prepare-windows-resource
|
||||||
@echo "Stopping MySQL test container..."
|
@printf 'Building Windows desktop...\n'
|
||||||
cd backend/tests/mysql && docker-compose down -v
|
ifeq ($(OS),Windows_NT)
|
||||||
|
powershell -NoProfile -Command "New-Item -ItemType Directory -Path 'build' -Force | Out-Null"
|
||||||
|
cd backend && set "CGO_ENABLED=1"&& set "GOOS=windows"&& set "GOARCH=amd64"&& go build -ldflags "$(GO_LDFLAGS_WIN)" -o ../build/nex-win-amd64.exe ./cmd/desktop
|
||||||
|
else
|
||||||
|
mkdir -p build
|
||||||
|
cd backend && CGO_ENABLED=1 GOOS=windows GOARCH=amd64 go build -ldflags "$(GO_LDFLAGS_WIN)" -o ../build/nex-win-amd64.exe ./cmd/desktop
|
||||||
|
endif
|
||||||
|
@printf 'Windows desktop build complete\n'
|
||||||
|
|
||||||
test-mysql: test-mysql-up
|
desktop-build-linux: version-check _desktop-prepare-frontend _desktop-prepare-embedfs
|
||||||
@echo "Running MySQL tests..."
|
@printf 'Building Linux desktop...\n'
|
||||||
cd backend && go test -tags=mysql ./tests/mysql/... -v -count=1
|
cd backend && CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -ldflags "$(GO_LDFLAGS)" -o ../build/nex-linux-amd64 ./cmd/desktop
|
||||||
$(MAKE) test-mysql-down
|
@printf 'Linux desktop build complete\n'
|
||||||
|
|
||||||
test-mysql-quick:
|
desktop-lint: _backend-lint _frontend-check
|
||||||
@echo "Running MySQL tests (without container management)..."
|
@printf 'Desktop lint complete\n'
|
||||||
cd backend && go test -tags=mysql ./tests/mysql/... -v -count=1
|
|
||||||
|
|
||||||
# ============================================
|
desktop-test: _desktop-test
|
||||||
# 前端
|
@printf 'Desktop tests passed\n'
|
||||||
# ============================================
|
|
||||||
|
|
||||||
frontend-install:
|
desktop-clean: _desktop-clean
|
||||||
cd frontend && bun install
|
@printf 'Desktop artifacts cleaned\n'
|
||||||
|
|
||||||
frontend-build: frontend-install
|
_desktop-test:
|
||||||
|
cd backend && go test ./cmd/desktop/... -v
|
||||||
|
|
||||||
|
_desktop-clean:
|
||||||
|
rm -rf build/ embedfs/assets embedfs/frontend-dist backend/cmd/desktop/rsrc_windows_amd64.syso
|
||||||
|
|
||||||
|
_desktop-prepare-frontend: _frontend-install
|
||||||
|
@printf 'Preparing frontend for desktop...\n'
|
||||||
|
ifeq ($(OS),Windows_NT)
|
||||||
|
powershell -NoProfile -Command "Copy-Item -LiteralPath 'frontend/.env.desktop' -Destination 'frontend/.env.production.local' -Force"
|
||||||
cd frontend && bun run build
|
cd frontend && bun run build
|
||||||
|
powershell -NoProfile -Command "Remove-Item -LiteralPath 'frontend/.env.production.local' -Force -ErrorAction SilentlyContinue"
|
||||||
frontend-dev: frontend-install
|
else
|
||||||
cd frontend && bun dev
|
|
||||||
|
|
||||||
frontend-test: frontend-install
|
|
||||||
cd frontend && bun run test
|
|
||||||
|
|
||||||
frontend-test-watch: frontend-install
|
|
||||||
cd frontend && bun run test:watch
|
|
||||||
|
|
||||||
frontend-test-coverage: frontend-install
|
|
||||||
cd frontend && bun run test:coverage
|
|
||||||
|
|
||||||
frontend-test-e2e: frontend-install
|
|
||||||
cd frontend && bun run test:e2e
|
|
||||||
|
|
||||||
frontend-lint: frontend-install
|
|
||||||
cd frontend && bun run lint
|
|
||||||
|
|
||||||
frontend-clean:
|
|
||||||
rm -rf frontend/dist frontend/.next frontend/node_modules
|
|
||||||
|
|
||||||
# ============================================
|
|
||||||
# 桌面应用
|
|
||||||
# ============================================
|
|
||||||
|
|
||||||
desktop-build: desktop-build-mac desktop-build-win desktop-build-linux
|
|
||||||
@echo "✅ Desktop builds complete for all platforms"
|
|
||||||
|
|
||||||
desktop-prepare-frontend:
|
|
||||||
@echo "📦 Preparing frontend for desktop..."
|
|
||||||
cd frontend && cp .env.desktop .env.production.local
|
cd frontend && cp .env.desktop .env.production.local
|
||||||
cd frontend && bun install && bun run build
|
cd frontend && bun run build
|
||||||
rm -f frontend/.env.production.local
|
rm -f frontend/.env.production.local
|
||||||
|
endif
|
||||||
|
|
||||||
desktop-prepare-embedfs:
|
_desktop-prepare-embedfs:
|
||||||
@echo "📦 Preparing embedded filesystem..."
|
@printf 'Preparing embedded filesystem...\n'
|
||||||
|
ifeq ($(OS),Windows_NT)
|
||||||
|
powershell -NoProfile -Command "Remove-Item -LiteralPath 'embedfs/assets' -Recurse -Force -ErrorAction SilentlyContinue; Remove-Item -LiteralPath 'embedfs/frontend-dist' -Recurse -Force -ErrorAction SilentlyContinue; Copy-Item -LiteralPath 'assets' -Destination 'embedfs/assets' -Recurse; Copy-Item -LiteralPath 'frontend/dist' -Destination 'embedfs/frontend-dist' -Recurse"
|
||||||
|
else
|
||||||
rm -rf embedfs/assets embedfs/frontend-dist
|
rm -rf embedfs/assets embedfs/frontend-dist
|
||||||
cp -r assets embedfs/assets
|
cp -r assets embedfs/assets
|
||||||
cp -r frontend/dist embedfs/frontend-dist
|
cp -r frontend/dist embedfs/frontend-dist
|
||||||
|
endif
|
||||||
|
|
||||||
desktop-build-mac: desktop-prepare-frontend desktop-prepare-embedfs
|
_desktop-prepare-windows-resource:
|
||||||
@echo "🍎 Building macOS..."
|
@printf 'Preparing Windows executable icon...\n'
|
||||||
cd backend && CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -o ../build/nex-mac-arm64 ./cmd/desktop
|
ifeq ($(OS),Windows_NT)
|
||||||
cd backend && CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -o ../build/nex-mac-amd64 ./cmd/desktop
|
cd backend/cmd/desktop && windres -O coff -F pe-x86-64 -i icon_windows.rc -o rsrc_windows_amd64.syso
|
||||||
|
else
|
||||||
desktop-build-win: desktop-prepare-frontend desktop-prepare-embedfs
|
@if command -v x86_64-w64-mingw32-windres >/dev/null 2>&1; then \
|
||||||
@echo "🪟 Building Windows..."
|
cd backend/cmd/desktop && x86_64-w64-mingw32-windres -O coff -F pe-x86-64 -i icon_windows.rc -o rsrc_windows_amd64.syso; \
|
||||||
cd backend && CGO_ENABLED=1 GOOS=windows GOARCH=amd64 go build -ldflags "-H=windowsgui" -o ../build/nex-win-amd64.exe ./cmd/desktop
|
elif command -v windres >/dev/null 2>&1; then \
|
||||||
|
cd backend/cmd/desktop && windres -O coff -F pe-x86-64 -i icon_windows.rc -o rsrc_windows_amd64.syso; \
|
||||||
desktop-build-linux: desktop-prepare-frontend desktop-prepare-embedfs
|
else \
|
||||||
@echo "🐧 Building Linux..."
|
printf 'Missing windres for Windows icon resource generation\n'; \
|
||||||
cd backend && CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o ../build/nex-linux-amd64 ./cmd/desktop
|
exit 1; \
|
||||||
|
fi
|
||||||
desktop-dev: desktop-prepare-frontend desktop-prepare-embedfs
|
endif
|
||||||
@echo "🖥️ Starting desktop app in dev mode..."
|
|
||||||
cd backend && go run ./cmd/desktop
|
|
||||||
|
|
||||||
desktop-test:
|
|
||||||
cd backend && go test ./cmd/desktop/... -v
|
|
||||||
|
|
||||||
desktop-package-mac:
|
|
||||||
./scripts/build/package-macos.sh
|
|
||||||
|
|
||||||
desktop-package-win:
|
|
||||||
@echo "⚠️ Windows packaging not implemented yet"
|
|
||||||
|
|
||||||
desktop-package-linux:
|
|
||||||
@echo "⚠️ Linux packaging not implemented yet"
|
|
||||||
|
|
||||||
desktop-clean:
|
|
||||||
rm -rf build/ embedfs/assets embedfs/frontend-dist
|
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# 清理
|
# 发布资产
|
||||||
# ============================================
|
# ============================================
|
||||||
|
|
||||||
clean: backend-clean frontend-clean desktop-clean
|
release-assets-check:
|
||||||
@echo "✅ Clean complete"
|
go run ./versionctl release-assets-check
|
||||||
|
@printf 'Release assets check passed\n'
|
||||||
|
|
||||||
|
release-assets-linux: version-check release-assets-check desktop-build-linux
|
||||||
|
rm -rf "$(RELEASE_DIR)"
|
||||||
|
mkdir -p "$(RELEASE_DIR)"
|
||||||
|
cd backend && CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -ldflags "$(GO_LDFLAGS)" -o ../build/nex-server-linux-amd64 ./cmd/server
|
||||||
|
tar -C build -czf "$(RELEASE_DIR)/$(SERVER_LINUX_ASSET)" nex-server-linux-amd64
|
||||||
|
tar -C build -czf "$(RELEASE_DIR)/$(DESKTOP_LINUX_ASSET)" nex-linux-amd64
|
||||||
|
|
||||||
|
release-assets-windows: version-check release-assets-check desktop-build-win
|
||||||
|
ifeq ($(OS),Windows_NT)
|
||||||
|
powershell -NoProfile -Command "Remove-Item -LiteralPath '$(RELEASE_DIR)' -Recurse -Force -ErrorAction SilentlyContinue; New-Item -ItemType Directory -Path '$(RELEASE_DIR)' -Force | Out-Null"
|
||||||
|
cd backend && set "CGO_ENABLED=1"&& set "GOOS=windows"&& set "GOARCH=amd64"&& go build -ldflags "$(GO_LDFLAGS_WIN)" -o ../build/nex-server-win-amd64.exe ./cmd/server
|
||||||
|
powershell -NoProfile -Command "Compress-Archive -LiteralPath 'build/nex-server-win-amd64.exe' -DestinationPath '$(RELEASE_DIR)/$(SERVER_WINDOWS_ASSET)' -Force"
|
||||||
|
powershell -NoProfile -Command "Compress-Archive -LiteralPath 'build/nex-win-amd64.exe' -DestinationPath '$(RELEASE_DIR)/$(DESKTOP_WINDOWS_ASSET)' -Force"
|
||||||
|
else
|
||||||
|
@printf 'release-assets-windows requires Windows\n'
|
||||||
|
@exit 1
|
||||||
|
endif
|
||||||
|
|
||||||
|
release-assets-macos: version-check release-assets-check desktop-build-mac
|
||||||
|
rm -rf "$(RELEASE_DIR)"
|
||||||
|
mkdir -p "$(RELEASE_DIR)"
|
||||||
|
cd backend && CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -ldflags "$(GO_LDFLAGS)" -o ../build/nex-server-darwin-amd64 ./cmd/server
|
||||||
|
cd backend && CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -ldflags "$(GO_LDFLAGS)" -o ../build/nex-server-darwin-arm64 ./cmd/server
|
||||||
|
tar -C build -czf "$(RELEASE_DIR)/$(SERVER_DARWIN_AMD64_ASSET)" nex-server-darwin-amd64
|
||||||
|
tar -C build -czf "$(RELEASE_DIR)/$(SERVER_DARWIN_ARM64_ASSET)" nex-server-darwin-arm64
|
||||||
|
ditto -c -k --keepParent build/Nex.app "$(RELEASE_DIR)/$(DESKTOP_MACOS_ASSET)"
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# 共享 helper targets
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
_backend-build:
|
||||||
|
@$(MAKE) -C backend build
|
||||||
|
|
||||||
|
_backend-lint:
|
||||||
|
@$(MAKE) -C backend lint
|
||||||
|
|
||||||
|
_backend-test:
|
||||||
|
@$(MAKE) -C backend test
|
||||||
|
|
||||||
|
_backend-clean:
|
||||||
|
@$(MAKE) -C backend clean
|
||||||
|
|
||||||
|
_versionctl-lint:
|
||||||
|
@$(MAKE) -C versionctl lint
|
||||||
|
|
||||||
|
_versionctl-test:
|
||||||
|
@$(MAKE) -C versionctl test
|
||||||
|
|
||||||
|
_frontend-install:
|
||||||
|
cd frontend && bun install
|
||||||
|
|
||||||
|
_frontend-build: _frontend-install
|
||||||
|
cd frontend && bun run build
|
||||||
|
|
||||||
|
_frontend-check: _frontend-install
|
||||||
|
cd frontend && bun run check
|
||||||
|
|
||||||
|
_frontend-test: _frontend-install
|
||||||
|
cd frontend && bun run test
|
||||||
|
|
||||||
|
_frontend-dev: _frontend-install
|
||||||
|
cd frontend && bun run dev
|
||||||
|
|
||||||
|
_frontend-clean:
|
||||||
|
rm -rf frontend/dist frontend/.next frontend/coverage frontend/playwright-report frontend/test-results frontend/tsconfig.tsbuildinfo
|
||||||
|
|||||||
178
README.md
@@ -36,13 +36,9 @@ nex/
|
|||||||
│
|
│
|
||||||
├── assets/ # 应用资源
|
├── assets/ # 应用资源
|
||||||
│ ├── icon.png # 托盘图标
|
│ ├── icon.png # 托盘图标
|
||||||
│ ├── AppIcon.icns # macOS 应用图标
|
│ ├── icon.icns # macOS 应用图标
|
||||||
│ └── icon.ico # Windows 应用图标
|
│ └── icon.ico # Windows 应用图标
|
||||||
│
|
│
|
||||||
├── scripts/ # 构建脚本
|
|
||||||
│ └── build/
|
|
||||||
│ └── package-macos.sh # macOS .app 打包脚本
|
|
||||||
│
|
|
||||||
└── README.md # 本文件
|
└── README.md # 本文件
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -51,7 +47,7 @@ nex/
|
|||||||
- **双协议支持**:同时支持 OpenAI 和 Anthropic 协议
|
- **双协议支持**:同时支持 OpenAI 和 Anthropic 协议
|
||||||
- **跨协议转换**:Hub-and-Spoke 架构实现 OpenAI ↔ Anthropic 双向转换
|
- **跨协议转换**:Hub-and-Spoke 架构实现 OpenAI ↔ Anthropic 双向转换
|
||||||
- **统一模型 ID**:`provider_id/model_name` 格式全局唯一标识模型(如 `openai/gpt-4`)
|
- **统一模型 ID**:`provider_id/model_name` 格式全局唯一标识模型(如 `openai/gpt-4`)
|
||||||
- **Smart Passthrough**:同协议请求零序列化开销,仅改写 model 字段
|
- **Smart Passthrough**:同协议请求跳过 Canonical 全量转换,仅在 JSON 层改写 model 字段
|
||||||
- **流式响应**:完整支持 SSE 流式传输,包括跨协议流式转换
|
- **流式响应**:完整支持 SSE 流式传输,包括跨协议流式转换
|
||||||
- **Function Calling**:支持工具调用(Tools)
|
- **Function Calling**:支持工具调用(Tools)
|
||||||
- **Thinking / Reasoning**:支持 OpenAI `reasoning_effort` 和 Anthropic `thinking` 配置
|
- **Thinking / Reasoning**:支持 OpenAI `reasoning_effort` 和 Anthropic `thinking` 配置
|
||||||
@@ -95,7 +91,7 @@ JSON: {"level":"info","logger":"handler.proxy","msg":"处理请求","method":
|
|||||||
- **图表库**: Recharts
|
- **图表库**: Recharts
|
||||||
- **路由**: React Router v7
|
- **路由**: React Router v7
|
||||||
- **数据获取**: TanStack Query v5
|
- **数据获取**: TanStack Query v5
|
||||||
- **样式**: SCSS Modules
|
- **样式**: TDesign 组件 props 优先,TDesign tokens 次之,SCSS 作为兜底补充
|
||||||
- **测试**: Vitest + React Testing Library + Playwright
|
- **测试**: Vitest + React Testing Library + Playwright
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
@@ -105,18 +101,14 @@ JSON: {"level":"info","logger":"handler.proxy","msg":"处理请求","method":
|
|||||||
**构建桌面应用**:
|
**构建桌面应用**:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# macOS (arm64 + amd64)
|
# macOS (arm64 + amd64,并打包为 .app)
|
||||||
make desktop-build-mac
|
make desktop-build-mac
|
||||||
make desktop-package-mac # 打包为 .app
|
|
||||||
|
|
||||||
# Windows
|
# Windows
|
||||||
make desktop-build-win
|
make desktop-build-win
|
||||||
|
|
||||||
# Linux
|
# Linux
|
||||||
make desktop-build-linux
|
make desktop-build-linux
|
||||||
|
|
||||||
# 构建所有平台
|
|
||||||
make desktop-build
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**使用桌面应用**:
|
**使用桌面应用**:
|
||||||
@@ -137,50 +129,54 @@ make desktop-build
|
|||||||
- Xfce: 需要 libappindicator
|
- Xfce: 需要 libappindicator
|
||||||
- 其他支持 StatusNotifierItem 规范的环境
|
- 其他支持 StatusNotifierItem 规范的环境
|
||||||
|
|
||||||
### CLI 模式
|
### Server 模式(前后端分离)
|
||||||
|
|
||||||
#### 后端
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd backend
|
make server-run
|
||||||
go mod download
|
|
||||||
go run cmd/server/main.go
|
|
||||||
```
|
```
|
||||||
|
|
||||||
后端服务将在 `http://localhost:9826` 启动。首次启动会自动:
|
`make server-run` 会并行启动:
|
||||||
|
- 后端服务:`http://localhost:9826`
|
||||||
|
- 前端开发服务器:`http://localhost:5173`
|
||||||
|
|
||||||
|
前端请求会继续通过 Vite proxy 转发到后端。后端首次启动会自动:
|
||||||
- 创建配置文件 `~/.nex/config.yaml`
|
- 创建配置文件 `~/.nex/config.yaml`
|
||||||
- 初始化数据库 `~/.nex/config.db`
|
- 初始化数据库 `~/.nex/config.db`
|
||||||
- 运行数据库迁移
|
- 运行数据库迁移
|
||||||
- 创建日志目录 `~/.nex/log/`
|
- 创建日志目录 `~/.nex/log/`
|
||||||
|
|
||||||
### 前端
|
**构建 server 模式产物**:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd frontend
|
make server-build
|
||||||
bun install
|
|
||||||
bun dev
|
|
||||||
```
|
```
|
||||||
|
|
||||||
前端开发服务器将在 `http://localhost:5173` 启动,API 请求通过 Vite proxy 转发到后端。
|
|
||||||
|
|
||||||
## API 接口
|
## API 接口
|
||||||
|
|
||||||
### 代理接口(对外部应用)
|
### 代理接口(对外部应用)
|
||||||
|
|
||||||
代理接口统一使用 `/{protocol}/*path` 路由格式,模型 ID 使用 `provider_id/model_name` 格式(如 `openai/gpt-4`)。同协议请求走 Smart Passthrough,最小化 JSON 改写保持参数保真;跨协议请求走完整 decode/encode 转换。
|
代理接口统一使用 `/{protocol}/*path` 路由格式,模型 ID 使用 `provider_id/model_name` 格式(如 `openai/gpt-4`)。同协议请求走 Smart Passthrough,最小化 JSON 改写并保持未改写字段的 JSON 内容和类型不变;跨协议请求走完整 decode/encode 转换。
|
||||||
|
|
||||||
**OpenAI 协议**(`protocol=openai`):
|
**OpenAI 协议**(`protocol=openai`):
|
||||||
- `POST /openai/chat/completions` - 对话补全
|
- `POST /openai/v1/chat/completions` - 对话补全
|
||||||
- `GET /openai/models` - 模型列表(本地数据库聚合)
|
- `GET /openai/v1/models` - 模型列表(本地数据库聚合)
|
||||||
- `GET /openai/models/{provider_id}/{model_name}` - 模型详情(本地数据库查询)
|
- `GET /openai/v1/models/{provider_id}/{model_name}` - 模型详情(本地数据库查询)
|
||||||
- `POST /openai/embeddings` - 嵌入
|
- `POST /openai/v1/embeddings` - 嵌入
|
||||||
- `POST /openai/rerank` - 重排序
|
- `POST /openai/v1/rerank` - 重排序
|
||||||
|
|
||||||
**Anthropic 协议**(`protocol=anthropic`):
|
**Anthropic 协议**(`protocol=anthropic`):
|
||||||
- `POST /anthropic/v1/messages` - 消息对话
|
- `POST /anthropic/v1/messages` - 消息对话
|
||||||
- `GET /anthropic/v1/models` - 模型列表(本地数据库聚合)
|
- `GET /anthropic/v1/models` - 模型列表(本地数据库聚合)
|
||||||
- `GET /anthropic/v1/models/{provider_id}/{model_name}` - 模型详情(本地数据库查询)
|
- `GET /anthropic/v1/models/{provider_id}/{model_name}` - 模型详情(本地数据库查询)
|
||||||
|
|
||||||
|
路径边界:网关只剥离第一段协议前缀,剩余路径保持协议原生形态交给 adapter。OpenAI adapter 接收 `/v1/chat/completions`、`/v1/models`、`/v1/embeddings`、`/v1/rerank`,并在构建上游 URL 时去掉 `/v1`;Anthropic adapter 接收 `/v1/messages`、`/v1/models`。因此 OpenAI 供应商 `base_url` 配置到版本路径一级(如 `https://api.openai.com/v1`),Anthropic 供应商 `base_url` 配置到域名级(如 `https://api.anthropic.com`)。
|
||||||
|
|
||||||
|
代理错误边界:网关层错误统一返回 `{"error":"...","code":"..."}`,例如 `INVALID_JSON`、`MODEL_NOT_FOUND`、`CONVERSION_FAILED`、`UPSTREAM_UNAVAILABLE`。只要上游已经返回 HTTP 响应,非 2xx 的 status、过滤 hop-by-hop header 后的 headers 和 body 会直接透传,不包装为应用错误或协议错误。
|
||||||
|
|
||||||
|
模型路由边界:只有 adapter 明确适配的接口会解析请求体中的 `model` 并使用统一模型 ID 路由;未知接口即使包含顶层 `model` 也按无 model 透传处理。
|
||||||
|
|
||||||
|
流式边界:同协议无响应 model 改写时原样透传 SSE frame 和 `[DONE]`;同协议需要响应 model 改写时只解析 SSE frame 的 `data` JSON 并改写 `model`;跨协议流式仍走 provider decoder → Canonical stream event → client encoder。
|
||||||
|
|
||||||
### 管理接口(对前端)
|
### 管理接口(对前端)
|
||||||
|
|
||||||
#### 供应商管理
|
#### 供应商管理
|
||||||
@@ -203,6 +199,9 @@ bun dev
|
|||||||
|
|
||||||
查询参数支持:`provider_id`、`model_name`、`start_date`、`end_date`、`group_by`
|
查询参数支持:`provider_id`、`model_name`、`start_date`、`end_date`、`group_by`
|
||||||
|
|
||||||
|
#### 版本信息
|
||||||
|
- `GET /api/version` - 获取后端构建版本信息(`version`、`commit`、`build_time`),用于前端 About 页面诊断前后端版本一致性
|
||||||
|
|
||||||
## 配置
|
## 配置
|
||||||
|
|
||||||
配置支持多种方式,优先级为:**CLI 参数 > 环境变量 > 配置文件 > 默认值**
|
配置支持多种方式,优先级为:**CLI 参数 > 环境变量 > 配置文件 > 默认值**
|
||||||
@@ -276,53 +275,100 @@ export NEX_DATABASE_DBNAME=nex
|
|||||||
## 测试
|
## 测试
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 顶层便捷命令
|
# 全局默认测试(不含 MySQL 和前端 E2E)
|
||||||
make test # 运行所有测试
|
make test
|
||||||
|
|
||||||
# 后端测试
|
# 产品级测试
|
||||||
make backend-test # 后端测试
|
make server-test
|
||||||
make backend-test-coverage # 后端覆盖率
|
make desktop-test
|
||||||
make backend-test-unit # 后端单元测试
|
|
||||||
make backend-test-integration # 后端集成测试
|
|
||||||
|
|
||||||
# 前端测试
|
|
||||||
make frontend-test # 前端测试
|
|
||||||
make frontend-test-e2e # 前端 E2E 测试
|
|
||||||
make frontend-test-coverage # 前端覆盖率
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
backend 分类测试、MySQL 专项测试和前端 E2E 测试请分别查看 `backend/README.md` 与 `frontend/README.md`。
|
||||||
|
|
||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 首次克隆后安装 Git hooks
|
# 首次克隆后安装 Git hooks
|
||||||
lefthook install
|
lefthook install
|
||||||
|
|
||||||
# 顶层便捷命令
|
# 全局命令
|
||||||
make dev # 启动开发环境(并行启动后端和前端)
|
make lint # 前后端共享检查
|
||||||
make build # 构建所有产物
|
make test # 默认全量测试(不含 MySQL/E2E)
|
||||||
make lint # 检查所有代码
|
make clean # 清理所有构建产物和测试报告
|
||||||
make clean # 清理所有构建产物
|
|
||||||
|
|
||||||
# 后端开发
|
# server 模式
|
||||||
make backend-build # 构建后端
|
make server-run # 并行启动后端和前端开发服务
|
||||||
make backend-run # 运行后端
|
make server-build # 构建 backend/bin/server 和 frontend/dist
|
||||||
make backend-dev # 后端开发模式
|
make server-lint # server 模式检查
|
||||||
make backend-lint # 后端代码检查
|
make server-test # server 模式测试
|
||||||
make backend-clean # 清理后端构建产物
|
make server-clean # 清理 server 模式产物
|
||||||
|
|
||||||
# 数据库操作
|
# desktop 模式
|
||||||
make backend-db-up # 数据库迁移
|
make desktop-build-mac # 构建 macOS 桌面应用
|
||||||
make backend-db-down # 数据库回滚
|
make desktop-build-win # 构建 Windows 桌面应用
|
||||||
make backend-db-status # 数据库迁移状态
|
make desktop-build-linux # 构建 Linux 桌面应用
|
||||||
make backend-db-create # 创建新迁移
|
make desktop-lint # desktop 模式检查
|
||||||
|
make desktop-test # desktop 专属测试
|
||||||
# 前端开发
|
make desktop-clean # 清理 desktop 产物
|
||||||
make frontend-build # 构建前端
|
|
||||||
make frontend-dev # 前端开发模式
|
|
||||||
make frontend-lint # 前端代码检查
|
|
||||||
make frontend-clean # 清理前端构建产物
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 版本与发布
|
||||||
|
|
||||||
|
### 统一版本源
|
||||||
|
|
||||||
|
- 仓库根目录 `VERSION` 是全仓唯一版本源,格式固定为 `x.y.z`
|
||||||
|
- `frontend/package.json` 和前端 `.env.*` 中的 `VITE_APP_VERSION` 由仓库工具同步,不能手工漂移
|
||||||
|
|
||||||
|
### 本地版本演进
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 递增版本(自动 sync + check + commit + tag)
|
||||||
|
make version-bump BUMP=minor
|
||||||
|
|
||||||
|
# 或指定具体版本号
|
||||||
|
make version-bump SET_VERSION=1.0.0
|
||||||
|
|
||||||
|
# 推送到远程
|
||||||
|
git push --follow-tags
|
||||||
|
```
|
||||||
|
|
||||||
|
手动同步和校验:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make version-sync
|
||||||
|
make version-check
|
||||||
|
```
|
||||||
|
|
||||||
|
### 本地生成发布资产
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Linux: server + desktop
|
||||||
|
make release-assets-linux
|
||||||
|
|
||||||
|
# Windows: server + desktop(需在 Windows 环境执行)
|
||||||
|
make release-assets-windows
|
||||||
|
|
||||||
|
# macOS: darwin-amd64 server、darwin-arm64 server、desktop universal
|
||||||
|
make release-assets-macos
|
||||||
|
```
|
||||||
|
|
||||||
|
生成的版本化发布资产位于 `build/release/`。
|
||||||
|
|
||||||
|
### GitHub Draft Release
|
||||||
|
|
||||||
|
- 推送 `vX.Y.Z` tag 后,`.github/workflows/release.yml` 会自动执行发布流水线
|
||||||
|
- 三个平台 job 会在正式构建前先检查 `go`、`bun` 和各自的平台打包工具链,缺失时快速失败并在日志中输出诊断信息
|
||||||
|
- Windows 发布 job 在 `MSYS2 / MINGW64` shell 中执行,并继承 `setup-go` / `setup-bun` 准备好的工具链路径
|
||||||
|
- 流水线会先校验 tag 与 `VERSION` 一致,再构建以下资产并上传到 GitHub Draft Release:
|
||||||
|
- Linux server
|
||||||
|
- Windows server
|
||||||
|
- darwin-amd64 server
|
||||||
|
- darwin-arm64 server
|
||||||
|
- Linux desktop
|
||||||
|
- Windows desktop
|
||||||
|
- macOS desktop universal
|
||||||
|
- Release 默认以 Draft 形式创建,需人工检查后再公开发布
|
||||||
|
|
||||||
## 开发规范
|
## 开发规范
|
||||||
|
|
||||||
详见各子项目的 README.md:
|
详见各子项目的 README.md:
|
||||||
@@ -331,4 +377,4 @@ make frontend-clean # 清理前端构建产物
|
|||||||
|
|
||||||
## 许可证
|
## 许可证
|
||||||
|
|
||||||
MIT
|
Apache License 2.0
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
# Assets
|
|
||||||
|
|
||||||
应用资源文件目录。
|
|
||||||
|
|
||||||
## 文件说明
|
|
||||||
|
|
||||||
| 文件 | 用途 | 尺寸 | 格式 |
|
|
||||||
|------|------|------|------|
|
|
||||||
| `icon.svg` | 源图标 | 64x64 | SVG |
|
|
||||||
| `icon.png` | 托盘图标 | 64x64 | PNG |
|
|
||||||
| `AppIcon.icns` | macOS 应用图标 | 多尺寸 | ICNS |
|
|
||||||
| `icon.ico` | Windows 应用图标 | 256x256 | ICO |
|
|
||||||
|
|
||||||
## 替换图标
|
|
||||||
|
|
||||||
### 1. 准备图标
|
|
||||||
|
|
||||||
推荐使用 SVG 格式的源图标,尺寸至少 256x256。
|
|
||||||
|
|
||||||
### 2. 生成各平台图标
|
|
||||||
|
|
||||||
**托盘图标 (PNG)**:
|
|
||||||
```bash
|
|
||||||
magick your-icon.svg -resize 64x64 icon.png
|
|
||||||
```
|
|
||||||
|
|
||||||
**macOS 应用图标 (ICNS)**:
|
|
||||||
```bash
|
|
||||||
mkdir icon.iconset
|
|
||||||
magick your-icon.svg -resize 16x16 icon.iconset/icon_16x16.png
|
|
||||||
magick your-icon.svg -resize 32x32 icon.iconset/icon_16x16@2x.png
|
|
||||||
magick your-icon.svg -resize 32x32 icon.iconset/icon_32x32.png
|
|
||||||
magick your-icon.svg -resize 64x64 icon.iconset/icon_32x32@2x.png
|
|
||||||
magick your-icon.svg -resize 128x128 icon.iconset/icon_128x128.png
|
|
||||||
magick your-icon.svg -resize 256x256 icon.iconset/icon_128x128@2x.png
|
|
||||||
iconutil -c icns icon.iconset -o AppIcon.icns
|
|
||||||
rm -rf icon.iconset
|
|
||||||
```
|
|
||||||
|
|
||||||
**Windows 应用图标 (ICO)**:
|
|
||||||
```bash
|
|
||||||
magick your-icon.svg -resize 256x256 icon.ico
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. 替换文件
|
|
||||||
|
|
||||||
将生成的文件放入此目录,然后重新构建桌面应用:
|
|
||||||
```bash
|
|
||||||
./scripts/build/build-darwin-arm64.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
## macOS Template 图标
|
|
||||||
|
|
||||||
macOS 支持 Template 图标,自动适配深浅色模式:
|
|
||||||
- 使用黑色 + 透明设计
|
|
||||||
- 文件名以 `Template` 结尾(如 `iconTemplate.png`)
|
|
||||||
- 黑色在深色模式下自动变为白色
|
|
||||||
|
|
||||||
## 设计建议
|
|
||||||
|
|
||||||
- 托盘图标应简洁,在小尺寸下清晰可辨
|
|
||||||
- 避免过多细节和文字
|
|
||||||
- 使用高对比度颜色
|
|
||||||
- macOS 建议使用 Template 图标风格
|
|
||||||
BIN
assets/icon.icns
LFS
Normal file
BIN
assets/icon.ico
|
Before Width: | Height: | Size: 264 KiB After Width: | Height: | Size: 130 B |
BIN
assets/icon.png
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 131 B |
@@ -1,13 +0,0 @@
|
|||||||
<svg width="64" height="64" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
|
||||||
<rect width="64" height="64" rx="12" fill="#4A90D9"/>
|
|
||||||
<polygon points="32,8 52,20 52,44 32,56 12,44 12,20" fill="none" stroke="white" stroke-width="3"/>
|
|
||||||
<circle cx="32" cy="32" r="6" fill="white"/>
|
|
||||||
<line x1="32" y1="32" x2="20" y2="20" stroke="white" stroke-width="2"/>
|
|
||||||
<line x1="32" y1="32" x2="44" y2="20" stroke="white" stroke-width="2"/>
|
|
||||||
<line x1="32" y1="32" x2="20" y2="44" stroke="white" stroke-width="2"/>
|
|
||||||
<line x1="32" y1="32" x2="44" y2="44" stroke="white" stroke-width="2"/>
|
|
||||||
<circle cx="20" cy="20" r="3" fill="white"/>
|
|
||||||
<circle cx="44" cy="20" r="3" fill="white"/>
|
|
||||||
<circle cx="20" cy="44" r="3" fill="white"/>
|
|
||||||
<circle cx="44" cy="44" r="3" fill="white"/>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 779 B |
BIN
assets/icons/hicolor/128x128/apps/nex.png
LFS
Normal file
BIN
assets/icons/hicolor/16x16/apps/nex.png
LFS
Normal file
BIN
assets/icons/hicolor/22x22/apps/nex.png
LFS
Normal file
BIN
assets/icons/hicolor/24x24/apps/nex.png
LFS
Normal file
BIN
assets/icons/hicolor/256x256/apps/nex.png
LFS
Normal file
BIN
assets/icons/hicolor/32x32/apps/nex.png
LFS
Normal file
BIN
assets/icons/hicolor/48x48/apps/nex.png
LFS
Normal file
BIN
assets/icons/hicolor/512x512/apps/nex.png
LFS
Normal file
BIN
assets/icons/hicolor/64x64/apps/nex.png
LFS
Normal file
97
backend/Makefile
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
.PHONY: \
|
||||||
|
build run \
|
||||||
|
test test-unit test-integration test-coverage \
|
||||||
|
lint clean \
|
||||||
|
migrate-up migrate-down migrate-status migrate-create \
|
||||||
|
mysql-up mysql-down mysql-test mysql-test-quick
|
||||||
|
|
||||||
|
VERSION := $(shell go run ../versionctl print)
|
||||||
|
GIT_COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || printf 'unknown')
|
||||||
|
BUILD_TIME ?= $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
GO_LDFLAGS := -X nex/backend/pkg/buildinfo.version=$(VERSION) -X nex/backend/pkg/buildinfo.commit=$(GIT_COMMIT) -X nex/backend/pkg/buildinfo.buildTime=$(BUILD_TIME)
|
||||||
|
|
||||||
|
DB_DRIVER ?= sqlite3
|
||||||
|
DB_DSN ?= $(HOME)/.nex/config.db
|
||||||
|
|
||||||
|
ifeq ($(DB_DRIVER),mysql)
|
||||||
|
GOOSE_DIR := migrations/mysql
|
||||||
|
GOOSE_DRIVER := mysql
|
||||||
|
else ifeq ($(DB_DRIVER),sqlite3)
|
||||||
|
GOOSE_DIR := migrations/sqlite
|
||||||
|
GOOSE_DRIVER := sqlite3
|
||||||
|
else
|
||||||
|
$(error unsupported DB_DRIVER '$(DB_DRIVER)', use sqlite3 or mysql)
|
||||||
|
endif
|
||||||
|
|
||||||
|
build:
|
||||||
|
go build -ldflags "$(GO_LDFLAGS)" -o bin/server ./cmd/server
|
||||||
|
|
||||||
|
run:
|
||||||
|
go run -ldflags "$(GO_LDFLAGS)" ./cmd/server
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test ./internal/... ./pkg/... ./tests/... ./cmd/server/... -v
|
||||||
|
|
||||||
|
test-unit:
|
||||||
|
go test ./internal/... ./pkg/... -v
|
||||||
|
|
||||||
|
test-integration:
|
||||||
|
go test ./tests/... -v
|
||||||
|
|
||||||
|
test-coverage:
|
||||||
|
go test ./... -coverprofile=coverage.out
|
||||||
|
go tool cover -html=coverage.out -o coverage.html
|
||||||
|
@printf 'Coverage report generated: backend/coverage.html\n'
|
||||||
|
|
||||||
|
lint:
|
||||||
|
go tool golangci-lint run ./...
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -rf bin/ coverage.out coverage.html
|
||||||
|
|
||||||
|
migrate-up:
|
||||||
|
@printf 'Running database migration up...\n'
|
||||||
|
goose -dir $(GOOSE_DIR) $(GOOSE_DRIVER) "$(DB_DSN)" up
|
||||||
|
|
||||||
|
migrate-down:
|
||||||
|
@printf 'Running database migration down...\n'
|
||||||
|
goose -dir $(GOOSE_DIR) $(GOOSE_DRIVER) "$(DB_DSN)" down
|
||||||
|
|
||||||
|
migrate-status:
|
||||||
|
@printf 'Checking database migration status...\n'
|
||||||
|
goose -dir $(GOOSE_DIR) $(GOOSE_DRIVER) "$(DB_DSN)" status
|
||||||
|
|
||||||
|
migrate-create:
|
||||||
|
@printf 'Migration name: '; \
|
||||||
|
read name; \
|
||||||
|
goose -dir migrations/sqlite create $$name sql; \
|
||||||
|
goose -dir migrations/mysql create $$name sql
|
||||||
|
|
||||||
|
mysql-up:
|
||||||
|
@printf 'Starting MySQL test container...\n'
|
||||||
|
cd tests/mysql && docker-compose up -d
|
||||||
|
@printf 'Waiting for MySQL to be ready...\n'
|
||||||
|
@for i in $$(seq 1 30); do \
|
||||||
|
if docker exec nex-mysql-test mysqladmin ping -h localhost -u root -ptestpass --silent 2>/dev/null; then \
|
||||||
|
printf 'MySQL is ready\n'; \
|
||||||
|
exit 0; \
|
||||||
|
fi; \
|
||||||
|
printf 'Waiting... (%s/30)\n' $$i; \
|
||||||
|
sleep 1; \
|
||||||
|
done; \
|
||||||
|
printf 'MySQL failed to start\n'; \
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
mysql-down:
|
||||||
|
@printf 'Stopping MySQL test container...\n'
|
||||||
|
cd tests/mysql && docker-compose down -v
|
||||||
|
|
||||||
|
mysql-test:
|
||||||
|
@set -e; \
|
||||||
|
$(MAKE) mysql-up; \
|
||||||
|
trap '$(MAKE) mysql-down' EXIT; \
|
||||||
|
go test -tags=mysql ./tests/mysql/... -v -count=1
|
||||||
|
|
||||||
|
mysql-test-quick:
|
||||||
|
@printf 'Running MySQL tests without container management...\n'
|
||||||
|
go test -tags=mysql ./tests/mysql/... -v -count=1
|
||||||
@@ -4,10 +4,10 @@ AI 网关后端服务,提供统一的大模型 API 代理接口。
|
|||||||
|
|
||||||
## 功能特性
|
## 功能特性
|
||||||
|
|
||||||
- 支持 OpenAI 协议(`/openai/v1/...`)
|
- 支持 OpenAI 协议(`/openai/v1/...`,例如 `/openai/v1/chat/completions`)
|
||||||
- 支持 Anthropic 协议(`/anthropic/v1/...`)
|
- 支持 Anthropic 协议(`/anthropic/v1/...`)
|
||||||
- 支持 Hub-and-Spoke 跨协议双向转换(OpenAI ↔ Anthropic)
|
- 支持 Hub-and-Spoke 跨协议双向转换(OpenAI ↔ Anthropic)
|
||||||
- 同协议透传(零语义损失、零序列化开销)
|
- 同协议透传(跳过 Canonical 全量转换,保持协议语义)
|
||||||
- 支持流式响应(SSE)
|
- 支持流式响应(SSE)
|
||||||
- 支持 Function Calling / Tools
|
- 支持 Function Calling / Tools
|
||||||
- 支持 Thinking / Reasoning
|
- 支持 Thinking / Reasoning
|
||||||
@@ -54,7 +54,7 @@ func NewProxyHandler(..., logger *zap.Logger) *ProxyHandler {
|
|||||||
使用 `pkg/logger/field.go` 中定义的字段构造函数:
|
使用 `pkg/logger/field.go` 中定义的字段构造函数:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
logger.Info("请求开始",
|
logger.Debug("请求开始",
|
||||||
pkglogger.Method("POST"),
|
pkglogger.Method("POST"),
|
||||||
pkglogger.Path("/v1/chat"),
|
pkglogger.Path("/v1/chat"),
|
||||||
pkglogger.RequestID("xxx"),
|
pkglogger.RequestID("xxx"),
|
||||||
@@ -220,7 +220,7 @@ OpenAI Response ← Canonical Response ← Anthropic Response
|
|||||||
|
|
||||||
### Smart Passthrough 机制
|
### Smart Passthrough 机制
|
||||||
|
|
||||||
同协议请求走 Smart Passthrough 路径,**零序列化开销**:
|
同协议请求走 Smart Passthrough 路径,不进入 Canonical 全量转换:
|
||||||
|
|
||||||
```
|
```
|
||||||
1. 检测 clientProtocol == providerProtocol
|
1. 检测 clientProtocol == providerProtocol
|
||||||
@@ -229,12 +229,14 @@ OpenAI Response ← Canonical Response ← Anthropic Response
|
|||||||
4. 响应中仅改写 model 字段:upstream_model_name → unified_id
|
4. 响应中仅改写 model 字段:upstream_model_name → unified_id
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Smart Passthrough 保持未改写 JSON 字段的内容和类型不变,不承诺保留原始字节顺序、空白或对象字段顺序。
|
||||||
|
|
||||||
### 流式转换器层次
|
### 流式转换器层次
|
||||||
|
|
||||||
```
|
```
|
||||||
StreamConverter (接口)
|
StreamConverter (接口)
|
||||||
├── PassthroughStreamConverter # 直接透传,无任何处理
|
├── PassthroughStreamConverter # 直接透传,无任何处理
|
||||||
├── SmartPassthroughStreamConverter # 同协议 + 逐 chunk 改写 model
|
├── SmartPassthroughStreamConverter # 同协议 + 按 SSE frame 改写 data JSON model
|
||||||
└── CanonicalStreamConverter # 跨协议完整转换(decode → encode)
|
└── CanonicalStreamConverter # 跨协议完整转换(decode → encode)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -301,6 +303,7 @@ StreamConverter (接口)
|
|||||||
| `PROTOCOL_CONSTRAINT_VIOLATION` | 协议约束违反 |
|
| `PROTOCOL_CONSTRAINT_VIOLATION` | 协议约束违反 |
|
||||||
| `ENCODING_FAILURE` | 编码失败 |
|
| `ENCODING_FAILURE` | 编码失败 |
|
||||||
| `INTERFACE_NOT_SUPPORTED` | 接口不支持(如 Anthropic Embeddings) |
|
| `INTERFACE_NOT_SUPPORTED` | 接口不支持(如 Anthropic Embeddings) |
|
||||||
|
| `UNSUPPORTED_MULTIMODAL` | 跨协议暂不支持多模态内容 |
|
||||||
|
|
||||||
### AppError 预定义错误
|
### AppError 预定义错误
|
||||||
|
|
||||||
@@ -434,24 +437,37 @@ docker run -d -e NEX_SERVER_PORT=9000 -e NEX_LOG_LEVEL=info nex-server
|
|||||||
## 测试
|
## 测试
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 运行所有测试
|
# 运行 backend 默认测试
|
||||||
make test
|
make test
|
||||||
|
|
||||||
|
# 分类测试
|
||||||
|
make test-unit
|
||||||
|
make test-integration
|
||||||
|
|
||||||
# 生成覆盖率报告
|
# 生成覆盖率报告
|
||||||
make test-coverage
|
make test-coverage
|
||||||
|
|
||||||
|
# MySQL 专项测试
|
||||||
|
make mysql-up
|
||||||
|
make mysql-down
|
||||||
|
make mysql-test
|
||||||
|
make mysql-test-quick
|
||||||
```
|
```
|
||||||
|
|
||||||
## 数据库迁移
|
## 数据库迁移
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 使用 Makefile
|
# 使用 Makefile
|
||||||
make migrate-up DB_PATH=~/.nex/config.db
|
make migrate-up DB_DSN=~/.nex/config.db
|
||||||
make migrate-down DB_PATH=~/.nex/config.db
|
make migrate-down DB_DSN=~/.nex/config.db
|
||||||
make migrate-status DB_PATH=~/.nex/config.db
|
make migrate-status DB_DSN=~/.nex/config.db
|
||||||
|
|
||||||
# 创建新迁移
|
# 创建新迁移
|
||||||
make migrate-create
|
make migrate-create
|
||||||
|
|
||||||
|
# MySQL 迁移
|
||||||
|
make migrate-up DB_DRIVER=mysql DB_DSN='user:pass@tcp(localhost:3306)/nex'
|
||||||
|
|
||||||
# 或直接使用 goose
|
# 或直接使用 goose
|
||||||
goose -dir migrations sqlite3 ~/.nex/config.db up
|
goose -dir migrations sqlite3 ~/.nex/config.db up
|
||||||
```
|
```
|
||||||
@@ -460,15 +476,15 @@ goose -dir migrations sqlite3 ~/.nex/config.db up
|
|||||||
|
|
||||||
### 代理接口
|
### 代理接口
|
||||||
|
|
||||||
使用 `/{protocol}/v1/{path}` URL 前缀路由:
|
使用 `/{protocol}/*path` URL 前缀路由。网关只剥离第一段协议前缀,不在 Handler 中统一添加或移除 `/v1`;剩余 path 是协议原生 nativePath,由对应 adapter 识别和组合上游 URL。
|
||||||
|
|
||||||
#### OpenAI 协议
|
#### OpenAI 协议
|
||||||
|
|
||||||
```
|
```
|
||||||
POST /openai/chat/completions
|
POST /openai/v1/chat/completions
|
||||||
GET /openai/models
|
GET /openai/v1/models
|
||||||
POST /openai/embeddings
|
POST /openai/v1/embeddings
|
||||||
POST /openai/rerank
|
POST /openai/v1/rerank
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Anthropic 协议
|
#### Anthropic 协议
|
||||||
@@ -478,10 +494,20 @@ POST /anthropic/v1/messages
|
|||||||
GET /anthropic/v1/models
|
GET /anthropic/v1/models
|
||||||
```
|
```
|
||||||
|
|
||||||
**协议转换**:网关支持任意协议间的双向转换。客户端使用 OpenAI 协议请求,上游供应商可以是 Anthropic 协议(反之亦然)。同协议时自动透传,零序列化开销。
|
**协议转换**:网关支持任意协议间的双向转换。客户端使用 OpenAI 协议请求,上游供应商可以是 Anthropic 协议(反之亦然)。同协议时自动透传或 Smart Passthrough,跳过 Canonical 全量转换。
|
||||||
|
|
||||||
**统一模型 ID**:代理请求中的 `model` 字段使用 `provider_id/model_name` 格式(如 `openai/gpt-4`),网关据此路由到对应供应商。同协议时自动改写为上游 `model_name`,跨协议时通过全量转换处理。
|
**统一模型 ID**:代理请求中的 `model` 字段使用 `provider_id/model_name` 格式(如 `openai/gpt-4`),网关据此路由到对应供应商。同协议时自动改写为上游 `model_name`,跨协议时通过全量转换处理。
|
||||||
|
|
||||||
|
**base_url 约定**:
|
||||||
|
- OpenAI 供应商配置到版本路径一级,例如 `https://api.openai.com/v1`;当客户端请求 `/openai/v1/chat/completions` 时,OpenAI adapter 会把 nativePath `/v1/chat/completions` 映射为上游 path `/chat/completions`,最终 URL 为 `https://api.openai.com/v1/chat/completions`。
|
||||||
|
- Anthropic 供应商配置到域名级,例如 `https://api.anthropic.com`。
|
||||||
|
|
||||||
|
**模型提取边界**:只有 adapter 明确适配的 Chat、Embeddings、Rerank 等接口会提取 `model` 并尝试统一模型 ID 路由。未知接口不做顶层 `model` 猜测,直接按无 model 透传。
|
||||||
|
|
||||||
|
**流式透传边界**:同协议无响应 model 改写时 raw passthrough,保留 SSE frame 边界和 `[DONE]`;同协议需要改写时按 SSE frame 解析 `data` JSON,仅改写 `model`;跨协议继续使用 StreamDecoder → CanonicalStreamConverter → StreamEncoder。
|
||||||
|
|
||||||
|
**错误边界**:网关层代理错误返回 `{"error":"...","code":"..."}`。已收到上游 HTTP 响应时,非 2xx status、过滤 hop-by-hop header 后的 headers 和 body 直接透传;没有收到上游响应的连接/DNS/TLS/超时错误返回 `UPSTREAM_UNAVAILABLE`。
|
||||||
|
|
||||||
### 管理接口
|
### 管理接口
|
||||||
|
|
||||||
#### 供应商管理
|
#### 供应商管理
|
||||||
@@ -509,7 +535,7 @@ GET /anthropic/v1/models
|
|||||||
- Anthropic 协议:配置到域名,不包含版本路径,如 `https://api.anthropic.com`
|
- Anthropic 协议:配置到域名,不包含版本路径,如 `https://api.anthropic.com`
|
||||||
|
|
||||||
**对外 URL 格式**:
|
**对外 URL 格式**:
|
||||||
- OpenAI 协议:`/{protocol}/{endpoint}`,如 `/openai/chat/completions`、`/openai/models`、`/openai/embeddings`
|
- OpenAI 协议:`/{protocol}/v1/{endpoint}`,如 `/openai/v1/chat/completions`、`/openai/v1/models`、`/openai/v1/embeddings`
|
||||||
- Anthropic 协议:`/{protocol}/v1/{endpoint}`,如 `/anthropic/v1/messages`、`/anthropic/v1/models`
|
- Anthropic 协议:`/{protocol}/v1/{endpoint}`,如 `/anthropic/v1/messages`、`/anthropic/v1/models`
|
||||||
|
|
||||||
#### 模型管理
|
#### 模型管理
|
||||||
@@ -551,6 +577,20 @@ GET /anthropic/v1/models
|
|||||||
|
|
||||||
查询参数:`provider_id`、`model_name`、`start_date`(YYYY-MM-DD)、`end_date`、`group_by`(provider/model/date)
|
查询参数:`provider_id`、`model_name`、`start_date`(YYYY-MM-DD)、`end_date`、`group_by`(provider/model/date)
|
||||||
|
|
||||||
|
#### 版本信息
|
||||||
|
|
||||||
|
- `GET /api/version` - 获取后端构建版本信息
|
||||||
|
|
||||||
|
响应字段来源于构建阶段注入的 `buildinfo` 元数据:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": "0.1.0",
|
||||||
|
"commit": "abc1234",
|
||||||
|
"build_time": "2026-05-05T00:00:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
#### 健康检查
|
#### 健康检查
|
||||||
|
|
||||||
- `GET /health` - 返回 `{"status": "ok"}`
|
- `GET /health` - 返回 `{"status": "ok"}`
|
||||||
@@ -558,9 +598,12 @@ GET /anthropic/v1/models
|
|||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
make build # 构建
|
make build # 构建 backend/bin/server
|
||||||
|
make run # 运行后端服务
|
||||||
make lint # 代码检查
|
make lint # 代码检查
|
||||||
make deps # 整理依赖
|
make clean # 清理 backend 构建产物
|
||||||
|
go mod tidy # 整理依赖
|
||||||
|
go generate ./... # 刷新 mock 等生成代码
|
||||||
```
|
```
|
||||||
|
|
||||||
环境要求:Go 1.26 或更高版本
|
环境要求:Go 1.26 或更高版本
|
||||||
|
|||||||
@@ -18,15 +18,6 @@ func showError(title, message string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func showAbout() {
|
|
||||||
message := "Nex Gateway\n\nAI Gateway - 统一的大模型 API 网关\n\nhttps://github.com/nex/gateway"
|
|
||||||
script := fmt.Sprintf(`display dialog "%s" buttons {"OK"} default button "OK" with title "关于 Nex Gateway"`,
|
|
||||||
escapeAppleScript(message))
|
|
||||||
if err := exec.Command("osascript", "-e", script).Run(); err != nil {
|
|
||||||
dialogLogger().Warn("显示关于对话框失败", zap.Error(err))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func escapeAppleScript(s string) string {
|
func escapeAppleScript(s string) string {
|
||||||
s = strings.ReplaceAll(s, "\\", "\\\\")
|
s = strings.ReplaceAll(s, "\\", "\\\\")
|
||||||
s = strings.ReplaceAll(s, "\"", "\\\"")
|
s = strings.ReplaceAll(s, "\"", "\\\"")
|
||||||
|
|||||||
@@ -65,23 +65,3 @@ func showError(title, message string) {
|
|||||||
dialogLogger().Error("无法显示错误对话框")
|
dialogLogger().Error("无法显示错误对话框")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func showAbout() {
|
|
||||||
message := "Nex Gateway\n\nAI Gateway - 统一的大模型 API 网关\n\nhttps://github.com/nex/gateway"
|
|
||||||
|
|
||||||
switch dialogTool {
|
|
||||||
case toolZenity:
|
|
||||||
exec.Command("zenity", "--info",
|
|
||||||
"--title=关于 Nex Gateway",
|
|
||||||
fmt.Sprintf("--text=%s", message)).Run()
|
|
||||||
case toolKdialog:
|
|
||||||
exec.Command("kdialog", "--msgbox", message, "--title", "关于 Nex Gateway").Run()
|
|
||||||
case toolNotifySend:
|
|
||||||
exec.Command("notify-send", "关于 Nex Gateway", message).Run()
|
|
||||||
case toolXmessage:
|
|
||||||
exec.Command("xmessage", "-center",
|
|
||||||
fmt.Sprintf("关于 Nex Gateway: %s", message)).Run()
|
|
||||||
default:
|
|
||||||
dialogLogger().Info("关于 Nex Gateway")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,36 +3,60 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
MB_ICONERROR = 0x10
|
mbIconError = 0x10
|
||||||
MB_ICONINFORMATION = 0x40
|
mbIconInformation = 0x40
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
user32 = syscall.NewLazyDLL("user32.dll")
|
user32 = syscall.NewLazyDLL("user32.dll")
|
||||||
procMessageBoxW = user32.NewProc("MessageBoxW")
|
procMessageBoxW = user32.NewProc("MessageBoxW")
|
||||||
|
callMessageBoxW = func(hwnd, text, caption, flags uintptr) (uintptr, error) {
|
||||||
|
ret, _, err := procMessageBoxW.Call(hwnd, text, caption, flags)
|
||||||
|
return ret, err
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func showError(title, message string) {
|
func showError(title, message string) {
|
||||||
messageBox(title, message, MB_ICONERROR)
|
if err := messageBox(title, message, mbIconError); err != nil {
|
||||||
|
if zapLogger != nil {
|
||||||
|
zapLogger.Warn("显示错误对话框失败", zap.Error(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func showAbout() {
|
func messageBox(title, message string, flags uint) error {
|
||||||
message := "Nex Gateway\n\nAI Gateway - 统一的大模型 API 网关\n\nhttps://github.com/nex/gateway"
|
titlePtr, err := syscall.UTF16PtrFromString(title)
|
||||||
messageBox("关于 Nex Gateway", message, MB_ICONINFORMATION)
|
if err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func messageBox(title, message string, flags uint) {
|
messagePtr, err := syscall.UTF16PtrFromString(message)
|
||||||
titlePtr, _ := syscall.UTF16PtrFromString(title)
|
if err != nil {
|
||||||
messagePtr, _ := syscall.UTF16PtrFromString(message)
|
return err
|
||||||
procMessageBoxW.Call(
|
}
|
||||||
|
|
||||||
|
ret, callErr := callMessageBoxW(
|
||||||
0,
|
0,
|
||||||
uintptr(unsafe.Pointer(messagePtr)),
|
uintptr(unsafe.Pointer(messagePtr)),
|
||||||
uintptr(unsafe.Pointer(titlePtr)),
|
uintptr(unsafe.Pointer(titlePtr)),
|
||||||
uintptr(flags),
|
uintptr(flags),
|
||||||
)
|
)
|
||||||
|
if ret != 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if callErr != nil && !errors.Is(callErr, syscall.Errno(0)) {
|
||||||
|
return callErr
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("MessageBoxW 调用失败")
|
||||||
}
|
}
|
||||||
|
|||||||
1
backend/cmd/desktop/icon_windows.rc
Normal file
@@ -0,0 +1 @@
|
|||||||
|
1 ICON "../../../assets/icon.ico"
|
||||||
@@ -25,6 +25,7 @@ import (
|
|||||||
"nex/backend/internal/provider"
|
"nex/backend/internal/provider"
|
||||||
"nex/backend/internal/repository"
|
"nex/backend/internal/repository"
|
||||||
"nex/backend/internal/service"
|
"nex/backend/internal/service"
|
||||||
|
"nex/backend/pkg/buildinfo"
|
||||||
|
|
||||||
"github.com/getlantern/systray"
|
"github.com/getlantern/systray"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -49,7 +50,7 @@ func main() {
|
|||||||
singleLock := NewSingletonLock(filepath.Join(os.TempDir(), "nex-gateway.lock"))
|
singleLock := NewSingletonLock(filepath.Join(os.TempDir(), "nex-gateway.lock"))
|
||||||
if err := singleLock.Lock(); err != nil {
|
if err := singleLock.Lock(); err != nil {
|
||||||
minimalLogger.Error("已有 Nex 实例运行")
|
minimalLogger.Error("已有 Nex 实例运行")
|
||||||
showError("Nex Gateway", "已有 Nex 实例运行")
|
showError(appName, "已有 Nex 实例运行")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
@@ -60,7 +61,7 @@ func main() {
|
|||||||
|
|
||||||
if err := checkPortAvailable(port); err != nil {
|
if err := checkPortAvailable(port); err != nil {
|
||||||
minimalLogger.Error("端口不可用", zap.Error(err))
|
minimalLogger.Error("端口不可用", zap.Error(err))
|
||||||
showError("Nex Gateway", err.Error())
|
showError(appName, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,6 +130,7 @@ func main() {
|
|||||||
providerHandler := handler.NewProviderHandler(providerService)
|
providerHandler := handler.NewProviderHandler(providerService)
|
||||||
modelHandler := handler.NewModelHandler(modelService)
|
modelHandler := handler.NewModelHandler(modelService)
|
||||||
statsHandler := handler.NewStatsHandler(statsService)
|
statsHandler := handler.NewStatsHandler(statsService)
|
||||||
|
versionHandler := handler.NewVersionHandler()
|
||||||
|
|
||||||
gin.SetMode(gin.ReleaseMode)
|
gin.SetMode(gin.ReleaseMode)
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
@@ -138,7 +140,7 @@ func main() {
|
|||||||
r.Use(middleware.Logging(zapLogger))
|
r.Use(middleware.Logging(zapLogger))
|
||||||
r.Use(middleware.CORS())
|
r.Use(middleware.CORS())
|
||||||
|
|
||||||
setupRoutes(r, proxyHandler, providerHandler, modelHandler, statsHandler)
|
setupRoutes(r, proxyHandler, providerHandler, modelHandler, statsHandler, versionHandler)
|
||||||
setupStaticFiles(r)
|
setupStaticFiles(r)
|
||||||
|
|
||||||
server = &http.Server{
|
server = &http.Server{
|
||||||
@@ -151,7 +153,11 @@ func main() {
|
|||||||
shutdownCtx, shutdownCancel = context.WithCancel(context.Background())
|
shutdownCtx, shutdownCancel = context.WithCancel(context.Background())
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
zapLogger.Info("AI Gateway 启动", zap.String("addr", server.Addr))
|
zapLogger.Info("AI Gateway 启动",
|
||||||
|
zap.String("addr", server.Addr),
|
||||||
|
zap.String("version", buildinfo.Version()),
|
||||||
|
zap.String("commit", buildinfo.Commit()),
|
||||||
|
zap.String("build_time", buildinfo.BuildTime()))
|
||||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
zapLogger.Fatal("服务器启动失败", zap.Error(err))
|
zapLogger.Fatal("服务器启动失败", zap.Error(err))
|
||||||
}
|
}
|
||||||
@@ -167,8 +173,10 @@ func main() {
|
|||||||
setupSystray(port)
|
setupSystray(port)
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupRoutes(r *gin.Engine, proxyHandler *handler.ProxyHandler, providerHandler *handler.ProviderHandler, modelHandler *handler.ModelHandler, statsHandler *handler.StatsHandler) {
|
func setupRoutes(r *gin.Engine, proxyHandler *handler.ProxyHandler, providerHandler *handler.ProviderHandler, modelHandler *handler.ModelHandler, statsHandler *handler.StatsHandler, versionHandler *handler.VersionHandler) {
|
||||||
r.Any("/v1/*path", proxyHandler.HandleProxy)
|
r.Any("/openai/*path", withProtocol("openai", proxyHandler.HandleProxy))
|
||||||
|
r.Any("/anthropic/*path", withProtocol("anthropic", proxyHandler.HandleProxy))
|
||||||
|
r.GET("/api/version", versionHandler.GetVersion)
|
||||||
|
|
||||||
providers := r.Group("/api/providers")
|
providers := r.Group("/api/providers")
|
||||||
{
|
{
|
||||||
@@ -199,12 +207,26 @@ func setupRoutes(r *gin.Engine, proxyHandler *handler.ProxyHandler, providerHand
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func withProtocol(protocol string, next gin.HandlerFunc) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
c.Params = append(c.Params, gin.Param{Key: "protocol", Value: protocol})
|
||||||
|
next(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func setupStaticFiles(r *gin.Engine) {
|
func setupStaticFiles(r *gin.Engine) {
|
||||||
distFS, err := fs.Sub(embedfs.FrontendDist, "frontend-dist")
|
distFS, err := frontendDistFS()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
zapLogger.Fatal("无法加载前端资源", zap.Error(err))
|
zapLogger.Fatal("无法加载前端资源", zap.Error(err))
|
||||||
}
|
}
|
||||||
|
setupStaticFilesWithFS(r, distFS)
|
||||||
|
}
|
||||||
|
|
||||||
|
func frontendDistFS() (fs.FS, error) {
|
||||||
|
return fs.Sub(embedfs.FrontendDist, "frontend-dist")
|
||||||
|
}
|
||||||
|
|
||||||
|
func setupStaticFilesWithFS(r *gin.Engine, distFS fs.FS) {
|
||||||
getContentType := func(path string) string {
|
getContentType := func(path string) string {
|
||||||
if strings.HasSuffix(path, ".js") {
|
if strings.HasSuffix(path, ".js") {
|
||||||
return "application/javascript"
|
return "application/javascript"
|
||||||
@@ -237,20 +259,23 @@ func setupStaticFiles(r *gin.Engine) {
|
|||||||
c.Data(200, getContentType(filepath), data)
|
c.Data(200, getContentType(filepath), data)
|
||||||
})
|
})
|
||||||
|
|
||||||
r.GET("/favicon.svg", func(c *gin.Context) {
|
r.GET("/icon.png", func(c *gin.Context) {
|
||||||
data, err := fs.ReadFile(distFS, "favicon.svg")
|
data, err := fs.ReadFile(distFS, "icon.png")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Status(404)
|
c.Status(404)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.Data(200, "image/svg+xml", data)
|
c.Data(200, "image/png", data)
|
||||||
})
|
})
|
||||||
|
|
||||||
r.NoRoute(func(c *gin.Context) {
|
r.NoRoute(func(c *gin.Context) {
|
||||||
path := c.Request.URL.Path
|
path := c.Request.URL.Path
|
||||||
|
|
||||||
if strings.HasPrefix(path, "/api/") ||
|
if strings.HasPrefix(path, "/api/") ||
|
||||||
strings.HasPrefix(path, "/v1/") ||
|
strings.HasPrefix(path, "/openai/") ||
|
||||||
|
strings.HasPrefix(path, "/anthropic/") ||
|
||||||
|
path == "/openai" ||
|
||||||
|
path == "/anthropic" ||
|
||||||
strings.HasPrefix(path, "/health") {
|
strings.HasPrefix(path, "/health") {
|
||||||
c.JSON(404, gin.H{"error": "not found"})
|
c.JSON(404, gin.H{"error": "not found"})
|
||||||
return
|
return
|
||||||
@@ -278,8 +303,7 @@ func setupSystray(port int) {
|
|||||||
zapLogger.Error("无法加载托盘图标", zap.Error(err))
|
zapLogger.Error("无法加载托盘图标", zap.Error(err))
|
||||||
}
|
}
|
||||||
systray.SetIcon(icon)
|
systray.SetIcon(icon)
|
||||||
systray.SetTitle("Nex Gateway")
|
systray.SetTooltip(appTooltip)
|
||||||
systray.SetTooltip("AI Gateway")
|
|
||||||
|
|
||||||
mOpen := systray.AddMenuItem("打开管理界面", "在浏览器中打开")
|
mOpen := systray.AddMenuItem("打开管理界面", "在浏览器中打开")
|
||||||
systray.AddSeparator()
|
systray.AddSeparator()
|
||||||
@@ -288,8 +312,6 @@ func setupSystray(port int) {
|
|||||||
mPort := systray.AddMenuItem(fmt.Sprintf("端口: %d", port), "")
|
mPort := systray.AddMenuItem(fmt.Sprintf("端口: %d", port), "")
|
||||||
mPort.Disable()
|
mPort.Disable()
|
||||||
systray.AddSeparator()
|
systray.AddSeparator()
|
||||||
mAbout := systray.AddMenuItem("关于", "")
|
|
||||||
systray.AddSeparator()
|
|
||||||
mQuit := systray.AddMenuItem("退出", "停止服务并退出")
|
mQuit := systray.AddMenuItem("退出", "停止服务并退出")
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -299,8 +321,6 @@ func setupSystray(port int) {
|
|||||||
if err := openBrowser(fmt.Sprintf("http://localhost:%d", port)); err != nil {
|
if err := openBrowser(fmt.Sprintf("http://localhost:%d", port)); err != nil {
|
||||||
zapLogger.Warn("打开浏览器失败", zap.Error(err))
|
zapLogger.Warn("打开浏览器失败", zap.Error(err))
|
||||||
}
|
}
|
||||||
case <-mAbout.ClickedCh:
|
|
||||||
showAbout()
|
|
||||||
case <-mQuit.ClickedCh:
|
case <-mQuit.ClickedCh:
|
||||||
doShutdown()
|
doShutdown()
|
||||||
systray.Quit()
|
systray.Quit()
|
||||||
|
|||||||
@@ -3,17 +3,59 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"syscall"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMessageBoxW_WindowsOnly(t *testing.T) {
|
func withMessageBoxW(t *testing.T, fn func(hwnd, text, caption, flags uintptr) (uintptr, error)) {
|
||||||
messageBox("测试标题", "测试消息", MB_ICONINFORMATION)
|
t.Helper()
|
||||||
|
|
||||||
|
old := callMessageBoxW
|
||||||
|
callMessageBoxW = fn
|
||||||
|
t.Cleanup(func() {
|
||||||
|
callMessageBoxW = old
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMessageBoxW_WindowsOnly_InvalidUTF16(t *testing.T) {
|
||||||
|
err := messageBox("bad\x00title", "测试消息", mbIconInformation)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("包含 NUL 字符时应该返回错误")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMessageBoxW_WindowsOnly_SuccessIgnoresLastError(t *testing.T) {
|
||||||
|
withMessageBoxW(t, func(_, _, _, _ uintptr) (uintptr, error) {
|
||||||
|
return 1, syscall.Errno(123)
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := messageBox("测试标题", "测试消息", mbIconInformation); err != nil {
|
||||||
|
t.Fatalf("MessageBoxW 返回成功时应忽略 last error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMessageBoxW_WindowsOnly_FailureUsesReturnValue(t *testing.T) {
|
||||||
|
withMessageBoxW(t, func(_, _, _, _ uintptr) (uintptr, error) {
|
||||||
|
return 0, syscall.Errno(5)
|
||||||
|
})
|
||||||
|
|
||||||
|
err := messageBox("测试标题", "测试消息", mbIconInformation)
|
||||||
|
if !errors.Is(err, syscall.Errno(5)) {
|
||||||
|
t.Fatalf("MessageBoxW 返回 0 时应返回调用错误: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestShowError_WindowsBranch(t *testing.T) {
|
func TestShowError_WindowsBranch(t *testing.T) {
|
||||||
|
withMessageBoxW(t, func(_, _, _, _ uintptr) (uintptr, error) {
|
||||||
|
return 0, syscall.Errno(5)
|
||||||
|
})
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if recovered := recover(); recovered != nil {
|
||||||
|
t.Fatalf("showError 不应因 MessageBoxW 失败而 panic: %v", recovered)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
showError("测试错误", "这是一条测试错误消息")
|
showError("测试错误", "这是一条测试错误消息")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestShowAbout_WindowsBranch(t *testing.T) {
|
|
||||||
showAbout()
|
|
||||||
}
|
|
||||||
|
|||||||
9
backend/cmd/desktop/metadata.go
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
const (
|
||||||
|
appName = "Nex"
|
||||||
|
appTooltip = appName
|
||||||
|
appDescription = "AI Gateway - 统一的大模型 API 网关"
|
||||||
|
// #nosec G101 -- 项目官网地址不是凭据
|
||||||
|
appWebsite = "https://github.com/nex/gateway"
|
||||||
|
)
|
||||||
13
backend/cmd/desktop/metadata_test.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestDesktopMetadata(t *testing.T) {
|
||||||
|
if appName != "Nex" {
|
||||||
|
t.Fatalf("appName = %q, want %q", appName, "Nex")
|
||||||
|
}
|
||||||
|
|
||||||
|
if appTooltip != appName {
|
||||||
|
t.Fatalf("appTooltip = %q, want %q", appTooltip, appName)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -21,19 +22,12 @@ func TestCheckPortAvailable(t *testing.T) {
|
|||||||
func TestCheckPortOccupied(t *testing.T) {
|
func TestCheckPortOccupied(t *testing.T) {
|
||||||
port := 19827
|
port := 19827
|
||||||
|
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:19827")
|
listener, err := net.Listen("tcp", ":19827") //nolint:gosec // 需要验证 checkPortAvailable 对通配地址占用的检测行为
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("无法启动测试服务器: %v", err)
|
t.Fatalf("无法启动测试服务器: %v", err)
|
||||||
}
|
}
|
||||||
defer listener.Close()
|
defer listener.Close()
|
||||||
|
|
||||||
go func() {
|
|
||||||
conn, err := listener.Accept()
|
|
||||||
if err == nil {
|
|
||||||
conn.Close()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
time.Sleep(100 * time.Millisecond)
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
err = checkPortAvailable(port)
|
err = checkPortAvailable(port)
|
||||||
@@ -56,7 +50,7 @@ func TestCheckPortAvailableAfterClose(t *testing.T) {
|
|||||||
defer server.Close()
|
defer server.Close()
|
||||||
go func() {
|
go func() {
|
||||||
err := server.Serve(listener)
|
err := server.Serve(listener)
|
||||||
if err != nil && err != http.ErrServerClosed {
|
if err != nil && err != http.ErrServerClosed && !errors.Is(err, net.ErrClosed) {
|
||||||
t.Errorf("serve failed: %v", err)
|
t.Errorf("serve failed: %v", err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|||||||
44
backend/cmd/desktop/routes_test.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"testing/fstest"
|
||||||
|
|
||||||
|
"nex/backend/internal/handler"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSetupRoutes_VersionDoesNotFallback(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
r := gin.New()
|
||||||
|
setupRoutes(r, &handler.ProxyHandler{}, &handler.ProviderHandler{}, &handler.ModelHandler{}, &handler.StatsHandler{}, handler.NewVersionHandler())
|
||||||
|
setupStaticFilesWithFS(r, fstest.MapFS{
|
||||||
|
"index.html": {Data: []byte("<html>fallback</html>")},
|
||||||
|
})
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/version", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
if contentType := w.Header().Get("Content-Type"); contentType == "text/html; charset=utf-8" {
|
||||||
|
t.Fatalf("版本接口不应返回 SPA fallback HTML")
|
||||||
|
}
|
||||||
|
|
||||||
|
var result map[string]string
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatalf("解析响应失败: %v", err)
|
||||||
|
}
|
||||||
|
for _, key := range []string{"version", "commit", "build_time"} {
|
||||||
|
if result[key] == "" {
|
||||||
|
t.Fatalf("响应缺少 %s 字段: %#v", key, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io/fs"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"testing/fstest"
|
||||||
"nex/embedfs"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -14,60 +13,14 @@ import (
|
|||||||
func TestSetupStaticFiles(t *testing.T) {
|
func TestSetupStaticFiles(t *testing.T) {
|
||||||
gin.SetMode(gin.TestMode)
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
distFS, err := fs.Sub(embedfs.FrontendDist, "frontend-dist")
|
distFS, err := frontendDistFS()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Skipf("跳过测试: 前端资源未构建: %v", err)
|
t.Skipf("跳过测试: 前端资源未构建: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
getContentType := func(path string) string {
|
|
||||||
if strings.HasSuffix(path, ".js") {
|
|
||||||
return "application/javascript"
|
|
||||||
}
|
|
||||||
if strings.HasSuffix(path, ".css") {
|
|
||||||
return "text/css"
|
|
||||||
}
|
|
||||||
if strings.HasSuffix(path, ".svg") {
|
|
||||||
return "image/svg+xml"
|
|
||||||
}
|
|
||||||
return "application/octet-stream"
|
|
||||||
}
|
|
||||||
|
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
r.GET("/assets/*filepath", func(c *gin.Context) {
|
setupStaticFilesWithFS(r, distFS)
|
||||||
filepath := c.Param("filepath")
|
|
||||||
data, err := fs.ReadFile(distFS, "assets"+filepath)
|
|
||||||
if err != nil {
|
|
||||||
c.Status(404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Data(200, getContentType(filepath), data)
|
|
||||||
})
|
|
||||||
|
|
||||||
r.GET("/favicon.svg", func(c *gin.Context) {
|
|
||||||
data, err := fs.ReadFile(distFS, "favicon.svg")
|
|
||||||
if err != nil {
|
|
||||||
c.Status(404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Data(200, "image/svg+xml", data)
|
|
||||||
})
|
|
||||||
|
|
||||||
r.NoRoute(func(c *gin.Context) {
|
|
||||||
path := c.Request.URL.Path
|
|
||||||
if strings.HasPrefix(path, "/api/") ||
|
|
||||||
strings.HasPrefix(path, "/v1/") ||
|
|
||||||
strings.HasPrefix(path, "/health") {
|
|
||||||
c.JSON(404, gin.H{"error": "not found"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data, err := fs.ReadFile(distFS, "index.html")
|
|
||||||
if err != nil {
|
|
||||||
c.Status(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Data(200, "text/html; charset=utf-8", data)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("API 404", func(t *testing.T) {
|
t.Run("API 404", func(t *testing.T) {
|
||||||
req := httptest.NewRequest("GET", "/api/test", nil)
|
req := httptest.NewRequest("GET", "/api/test", nil)
|
||||||
@@ -79,6 +32,32 @@ func TestSetupStaticFiles(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("OpenAI proxy prefix 404", func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest("GET", "/openai/", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("期望状态码 404, 实际 %d", w.Code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(w.Body.String(), "not found") {
|
||||||
|
t.Errorf("期望返回 API 风格错误,实际 %s", w.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Anthropic proxy prefix 404", func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest("GET", "/anthropic/", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("期望状态码 404, 实际 %d", w.Code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(w.Body.String(), "not found") {
|
||||||
|
t.Errorf("期望返回 API 风格错误,实际 %s", w.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
t.Run("SPA fallback", func(t *testing.T) {
|
t.Run("SPA fallback", func(t *testing.T) {
|
||||||
req := httptest.NewRequest("GET", "/providers", nil)
|
req := httptest.NewRequest("GET", "/providers", nil)
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
@@ -121,3 +100,139 @@ func TestSetupStaticFiles(t *testing.T) {
|
|||||||
|
|
||||||
t.Log("静态文件服务测试通过")
|
t.Log("静态文件服务测试通过")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSetupStaticFilesWithFS_IconPNG(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
r := gin.New()
|
||||||
|
setupStaticFilesWithFS(r, fstest.MapFS{
|
||||||
|
"icon.png": {Data: []byte("png")},
|
||||||
|
"index.html": {Data: []byte("<html>fallback</html>")},
|
||||||
|
})
|
||||||
|
|
||||||
|
req := httptest.NewRequest("GET", "/icon.png", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("期望状态码 200, 实际 %d", w.Code)
|
||||||
|
}
|
||||||
|
if w.Header().Get("Content-Type") != "image/png" {
|
||||||
|
t.Fatalf("期望 Content-Type image/png, 实际 %s", w.Header().Get("Content-Type"))
|
||||||
|
}
|
||||||
|
if w.Body.String() != "png" {
|
||||||
|
t.Fatalf("期望返回 PNG 内容,实际 %q", w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithProtocolAndStaticRoutes(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
distFS, err := frontendDistFS()
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("跳过测试: 前端资源未构建: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r := gin.New()
|
||||||
|
|
||||||
|
var gotProtocol string
|
||||||
|
var gotPath string
|
||||||
|
r.Any("/openai/*path", withProtocol("openai", func(c *gin.Context) {
|
||||||
|
gotProtocol = c.Param("protocol")
|
||||||
|
gotPath = c.Param("path")
|
||||||
|
c.JSON(http.StatusOK, gin.H{"protocol": gotProtocol, "path": gotPath})
|
||||||
|
}))
|
||||||
|
r.Any("/anthropic/*path", withProtocol("anthropic", func(c *gin.Context) {
|
||||||
|
gotProtocol = c.Param("protocol")
|
||||||
|
gotPath = c.Param("path")
|
||||||
|
c.JSON(http.StatusOK, gin.H{"protocol": gotProtocol, "path": gotPath})
|
||||||
|
}))
|
||||||
|
setupStaticFilesWithFS(r, distFS)
|
||||||
|
|
||||||
|
t.Run("OpenAI route enters proxy handler wrapper", func(t *testing.T) {
|
||||||
|
gotProtocol = ""
|
||||||
|
gotPath = ""
|
||||||
|
|
||||||
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("期望状态码 200, 实际 %d", w.Code)
|
||||||
|
}
|
||||||
|
if gotProtocol != "openai" {
|
||||||
|
t.Errorf("期望 protocol=openai, 实际 %s", gotProtocol)
|
||||||
|
}
|
||||||
|
if gotPath != "/v1/chat/completions" {
|
||||||
|
t.Errorf("期望 path=/v1/chat/completions, 实际 %s", gotPath)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Anthropic route enters proxy handler wrapper", func(t *testing.T) {
|
||||||
|
gotProtocol = ""
|
||||||
|
gotPath = ""
|
||||||
|
|
||||||
|
req := httptest.NewRequest("POST", "/anthropic/v1/messages", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("期望状态码 200, 实际 %d", w.Code)
|
||||||
|
}
|
||||||
|
if gotProtocol != "anthropic" {
|
||||||
|
t.Errorf("期望 protocol=anthropic, 实际 %s", gotProtocol)
|
||||||
|
}
|
||||||
|
if gotPath != "/v1/messages" {
|
||||||
|
t.Errorf("期望 path=/v1/messages, 实际 %s", gotPath)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Static assets are not hijacked", func(t *testing.T) {
|
||||||
|
gotProtocol = ""
|
||||||
|
gotPath = ""
|
||||||
|
|
||||||
|
req := httptest.NewRequest("GET", "/assets/test.js", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if gotProtocol != "" || gotPath != "" {
|
||||||
|
t.Errorf("静态资源不应进入代理包装器,实际 protocol=%s path=%s", gotProtocol, gotPath)
|
||||||
|
}
|
||||||
|
if w.Code == http.StatusOK {
|
||||||
|
if !strings.HasPrefix(w.Header().Get("Content-Type"), "application/javascript") {
|
||||||
|
t.Errorf("期望 JS Content-Type, 实际 %s", w.Header().Get("Content-Type"))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if w.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("期望静态资源返回 200 或 404, 实际 %d", w.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("SPA path keeps fallback", func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest("GET", "/providers", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("期望状态码 200, 实际 %d", w.Code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(w.Header().Get("Content-Type"), "text/html") {
|
||||||
|
t.Errorf("期望返回 HTML,实际 %s", w.Header().Get("Content-Type"))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Unknown proxy-like path does not return index html", func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest("GET", "/openai/unknown", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("显式代理路由应进入代理包装器,实际状态码 %d", w.Code)
|
||||||
|
}
|
||||||
|
if gotProtocol != "openai" || gotPath != "/unknown" {
|
||||||
|
t.Errorf("期望 unknown 代理路径进入 openai 包装器,实际 protocol=%s path=%s", gotProtocol, gotPath)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import (
|
|||||||
"nex/backend/internal/provider"
|
"nex/backend/internal/provider"
|
||||||
"nex/backend/internal/repository"
|
"nex/backend/internal/repository"
|
||||||
"nex/backend/internal/service"
|
"nex/backend/internal/service"
|
||||||
|
"nex/backend/pkg/buildinfo"
|
||||||
pkgLogger "nex/backend/pkg/logger"
|
pkgLogger "nex/backend/pkg/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -92,6 +93,7 @@ func main() {
|
|||||||
providerHandler := handler.NewProviderHandler(providerService)
|
providerHandler := handler.NewProviderHandler(providerService)
|
||||||
modelHandler := handler.NewModelHandler(modelService)
|
modelHandler := handler.NewModelHandler(modelService)
|
||||||
statsHandler := handler.NewStatsHandler(statsService)
|
statsHandler := handler.NewStatsHandler(statsService)
|
||||||
|
versionHandler := handler.NewVersionHandler()
|
||||||
|
|
||||||
gin.SetMode(gin.ReleaseMode)
|
gin.SetMode(gin.ReleaseMode)
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
@@ -101,7 +103,7 @@ func main() {
|
|||||||
r.Use(middleware.Logging(zapLogger))
|
r.Use(middleware.Logging(zapLogger))
|
||||||
r.Use(middleware.CORS())
|
r.Use(middleware.CORS())
|
||||||
|
|
||||||
setupRoutes(r, proxyHandler, providerHandler, modelHandler, statsHandler)
|
setupRoutes(r, proxyHandler, providerHandler, modelHandler, statsHandler, versionHandler)
|
||||||
|
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
Addr: fmt.Sprintf(":%d", cfg.Server.Port),
|
Addr: fmt.Sprintf(":%d", cfg.Server.Port),
|
||||||
@@ -111,7 +113,11 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
zapLogger.Info("AI Gateway 启动", zap.String("addr", srv.Addr))
|
zapLogger.Info("AI Gateway 启动",
|
||||||
|
zap.String("addr", srv.Addr),
|
||||||
|
zap.String("version", buildinfo.Version()),
|
||||||
|
zap.String("commit", buildinfo.Commit()),
|
||||||
|
zap.String("build_time", buildinfo.BuildTime()))
|
||||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
zapLogger.Fatal("服务器启动失败", zap.Error(err))
|
zapLogger.Fatal("服务器启动失败", zap.Error(err))
|
||||||
}
|
}
|
||||||
@@ -135,8 +141,9 @@ func main() {
|
|||||||
zapLogger.Info("服务器已关闭")
|
zapLogger.Info("服务器已关闭")
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupRoutes(r *gin.Engine, proxyHandler *handler.ProxyHandler, providerHandler *handler.ProviderHandler, modelHandler *handler.ModelHandler, statsHandler *handler.StatsHandler) {
|
func setupRoutes(r *gin.Engine, proxyHandler *handler.ProxyHandler, providerHandler *handler.ProviderHandler, modelHandler *handler.ModelHandler, statsHandler *handler.StatsHandler, versionHandler *handler.VersionHandler) {
|
||||||
r.Any("/:protocol/*path", proxyHandler.HandleProxy)
|
r.Any("/:protocol/*path", proxyHandler.HandleProxy)
|
||||||
|
r.GET("/api/version", versionHandler.GetVersion)
|
||||||
|
|
||||||
providers := r.Group("/api/providers")
|
providers := r.Group("/api/providers")
|
||||||
{
|
{
|
||||||
|
|||||||
37
backend/cmd/server/routes_test.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"nex/backend/internal/handler"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSetupRoutes_Version(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
r := gin.New()
|
||||||
|
setupRoutes(r, &handler.ProxyHandler{}, &handler.ProviderHandler{}, &handler.ModelHandler{}, &handler.StatsHandler{}, handler.NewVersionHandler())
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/version", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
var result map[string]string
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatalf("解析响应失败: %v", err)
|
||||||
|
}
|
||||||
|
for _, key := range []string{"version", "commit", "build_time"} {
|
||||||
|
if result[key] == "" {
|
||||||
|
t.Fatalf("响应缺少 %s 字段: %#v", key, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -49,6 +49,28 @@ func TestAdapter_DetectInterfaceType(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdapter_APIReferenceNativePaths(t *testing.T) {
|
||||||
|
a := NewAdapter()
|
||||||
|
|
||||||
|
// docs/api_reference/anthropic defines messages and models under /v1.
|
||||||
|
tests := []struct {
|
||||||
|
path string
|
||||||
|
expected conversion.InterfaceType
|
||||||
|
}{
|
||||||
|
{"/v1/messages", conversion.InterfaceTypeChat},
|
||||||
|
{"/v1/models", conversion.InterfaceTypeModels},
|
||||||
|
{"/v1/models/claude-sonnet-4-5", conversion.InterfaceTypeModelInfo},
|
||||||
|
{"/messages", conversion.InterfaceTypePassthrough},
|
||||||
|
{"/models", conversion.InterfaceTypePassthrough},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.path, func(t *testing.T) {
|
||||||
|
assert.Equal(t, tt.expected, a.DetectInterfaceType(tt.path))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAdapter_BuildUrl(t *testing.T) {
|
func TestAdapter_BuildUrl(t *testing.T) {
|
||||||
a := NewAdapter()
|
a := NewAdapter()
|
||||||
|
|
||||||
|
|||||||
@@ -51,15 +51,23 @@ func (e *StreamEncoder) encodeMessageStart(event canonical.CanonicalStreamEvent)
|
|||||||
if event.Message != nil {
|
if event.Message != nil {
|
||||||
msg := map[string]any{
|
msg := map[string]any{
|
||||||
"id": event.Message.ID,
|
"id": event.Message.ID,
|
||||||
"model": event.Message.Model,
|
"type": "message",
|
||||||
"role": "assistant",
|
"role": "assistant",
|
||||||
|
"content": []any{},
|
||||||
|
"model": event.Message.Model,
|
||||||
|
"stop_reason": nil,
|
||||||
|
"stop_sequence": nil,
|
||||||
}
|
}
|
||||||
if event.Message.Usage != nil {
|
if event.Message.Usage != nil {
|
||||||
usage := map[string]any{
|
msg["usage"] = map[string]any{
|
||||||
"input_tokens": event.Message.Usage.InputTokens,
|
"input_tokens": event.Message.Usage.InputTokens,
|
||||||
"output_tokens": event.Message.Usage.OutputTokens,
|
"output_tokens": event.Message.Usage.OutputTokens,
|
||||||
}
|
}
|
||||||
msg["usage"] = usage
|
} else {
|
||||||
|
msg["usage"] = map[string]any{
|
||||||
|
"input_tokens": 0,
|
||||||
|
"output_tokens": 0,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
payload["message"] = msg
|
payload["message"] = msg
|
||||||
}
|
}
|
||||||
@@ -147,6 +155,10 @@ func (e *StreamEncoder) encodeMessageDelta(event canonical.CanonicalStreamEvent)
|
|||||||
payload["usage"] = map[string]any{
|
payload["usage"] = map[string]any{
|
||||||
"output_tokens": event.Usage.OutputTokens,
|
"output_tokens": event.Usage.OutputTokens,
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
payload["usage"] = map[string]any{
|
||||||
|
"output_tokens": 0,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return e.marshalEvent("message_delta", payload)
|
return e.marshalEvent("message_delta", payload)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,8 +21,55 @@ func TestStreamEncoder_MessageStart(t *testing.T) {
|
|||||||
s := string(chunks[0])
|
s := string(chunks[0])
|
||||||
assert.True(t, strings.HasPrefix(s, "event: message_start\n"))
|
assert.True(t, strings.HasPrefix(s, "event: message_start\n"))
|
||||||
assert.Contains(t, s, "data: ")
|
assert.Contains(t, s, "data: ")
|
||||||
assert.Contains(t, s, "msg_1")
|
|
||||||
assert.Contains(t, s, "claude-3")
|
var payload map[string]any
|
||||||
|
lines := strings.Split(s, "\n")
|
||||||
|
for _, l := range lines {
|
||||||
|
if strings.HasPrefix(l, "data: ") {
|
||||||
|
require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(l, "data: ")), &payload))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
msg, ok := payload["message"].(map[string]any)
|
||||||
|
require.True(t, ok)
|
||||||
|
assert.Equal(t, "msg_1", msg["id"])
|
||||||
|
assert.Equal(t, "message", msg["type"])
|
||||||
|
assert.Equal(t, "assistant", msg["role"])
|
||||||
|
assert.Equal(t, []any{}, msg["content"])
|
||||||
|
assert.Equal(t, "claude-3", msg["model"])
|
||||||
|
assert.Nil(t, msg["stop_reason"])
|
||||||
|
assert.Nil(t, msg["stop_sequence"])
|
||||||
|
|
||||||
|
usage, okU := msg["usage"].(map[string]any)
|
||||||
|
require.True(t, okU)
|
||||||
|
assert.Equal(t, float64(0), usage["input_tokens"])
|
||||||
|
assert.Equal(t, float64(0), usage["output_tokens"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStreamEncoder_MessageStart_WithUsage(t *testing.T) {
|
||||||
|
e := NewStreamEncoder()
|
||||||
|
event := canonical.NewMessageStartEventWithUsage("msg_2", "gpt-4", &canonical.CanonicalUsage{InputTokens: 100, OutputTokens: 50})
|
||||||
|
|
||||||
|
chunks := e.EncodeEvent(event)
|
||||||
|
require.Len(t, chunks, 1)
|
||||||
|
|
||||||
|
s := string(chunks[0])
|
||||||
|
var payload map[string]any
|
||||||
|
lines := strings.Split(s, "\n")
|
||||||
|
for _, l := range lines {
|
||||||
|
if strings.HasPrefix(l, "data: ") {
|
||||||
|
require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(l, "data: ")), &payload))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
msg, ok := payload["message"].(map[string]any)
|
||||||
|
require.True(t, ok)
|
||||||
|
usage, okU := msg["usage"].(map[string]any)
|
||||||
|
require.True(t, okU)
|
||||||
|
assert.Equal(t, float64(100), usage["input_tokens"])
|
||||||
|
assert.Equal(t, float64(50), usage["output_tokens"])
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStreamEncoder_ContentBlockDelta(t *testing.T) {
|
func TestStreamEncoder_ContentBlockDelta(t *testing.T) {
|
||||||
@@ -179,6 +226,10 @@ func TestStreamEncoder_MessageDelta_WithStopReason(t *testing.T) {
|
|||||||
delta, okd := payload["delta"].(map[string]any)
|
delta, okd := payload["delta"].(map[string]any)
|
||||||
require.True(t, okd)
|
require.True(t, okd)
|
||||||
assert.Equal(t, "end_turn", delta["stop_reason"])
|
assert.Equal(t, "end_turn", delta["stop_reason"])
|
||||||
|
|
||||||
|
usage, oku := payload["usage"].(map[string]any)
|
||||||
|
require.True(t, oku, "message_delta SHALL always include usage")
|
||||||
|
assert.Equal(t, float64(0), usage["output_tokens"])
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStreamEncoder_MessageDelta_WithUsage(t *testing.T) {
|
func TestStreamEncoder_MessageDelta_WithUsage(t *testing.T) {
|
||||||
|
|||||||
@@ -3,11 +3,13 @@ package conversion
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
|
|
||||||
|
"nex/backend/internal/conversion/canonical"
|
||||||
pkglogger "nex/backend/pkg/logger"
|
pkglogger "nex/backend/pkg/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -71,7 +73,7 @@ func (e *ConversionEngine) IsPassthrough(clientProtocol, providerProtocol string
|
|||||||
|
|
||||||
// ConvertHttpRequest 转换 HTTP 请求
|
// ConvertHttpRequest 转换 HTTP 请求
|
||||||
func (e *ConversionEngine) ConvertHttpRequest(spec HTTPRequestSpec, clientProtocol, providerProtocol string, provider *TargetProvider) (*HTTPRequestSpec, error) {
|
func (e *ConversionEngine) ConvertHttpRequest(spec HTTPRequestSpec, clientProtocol, providerProtocol string, provider *TargetProvider) (*HTTPRequestSpec, error) {
|
||||||
nativePath := spec.URL
|
nativePath, rawQuery := splitRequestPath(spec.URL)
|
||||||
|
|
||||||
if e.IsPassthrough(clientProtocol, providerProtocol) {
|
if e.IsPassthrough(clientProtocol, providerProtocol) {
|
||||||
providerAdapter, err := e.registry.Get(providerProtocol)
|
providerAdapter, err := e.registry.Get(providerProtocol)
|
||||||
@@ -96,8 +98,11 @@ func (e *ConversionEngine) ConvertHttpRequest(spec HTTPRequestSpec, clientProtoc
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
providerURL := providerAdapter.BuildUrl(nativePath, interfaceType)
|
||||||
|
providerURL = appendRawQuery(providerURL, rawQuery)
|
||||||
|
|
||||||
return &HTTPRequestSpec{
|
return &HTTPRequestSpec{
|
||||||
URL: provider.BaseURL + nativePath,
|
URL: joinBaseURL(provider.BaseURL, providerURL),
|
||||||
Method: spec.Method,
|
Method: spec.Method,
|
||||||
Headers: providerAdapter.BuildHeaders(provider),
|
Headers: providerAdapter.BuildHeaders(provider),
|
||||||
Body: rewrittenBody,
|
Body: rewrittenBody,
|
||||||
@@ -115,6 +120,7 @@ func (e *ConversionEngine) ConvertHttpRequest(spec HTTPRequestSpec, clientProtoc
|
|||||||
|
|
||||||
interfaceType := clientAdapter.DetectInterfaceType(nativePath)
|
interfaceType := clientAdapter.DetectInterfaceType(nativePath)
|
||||||
providerURL := providerAdapter.BuildUrl(nativePath, interfaceType)
|
providerURL := providerAdapter.BuildUrl(nativePath, interfaceType)
|
||||||
|
providerURL = appendRawQuery(providerURL, rawQuery)
|
||||||
providerHeaders := providerAdapter.BuildHeaders(provider)
|
providerHeaders := providerAdapter.BuildHeaders(provider)
|
||||||
providerBody, err := e.convertBody(interfaceType, clientAdapter, providerAdapter, provider, spec.Body)
|
providerBody, err := e.convertBody(interfaceType, clientAdapter, providerAdapter, provider, spec.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -122,7 +128,7 @@ func (e *ConversionEngine) ConvertHttpRequest(spec HTTPRequestSpec, clientProtoc
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &HTTPRequestSpec{
|
return &HTTPRequestSpec{
|
||||||
URL: provider.BaseURL + providerURL,
|
URL: joinBaseURL(provider.BaseURL, providerURL),
|
||||||
Method: spec.Method,
|
Method: spec.Method,
|
||||||
Headers: providerHeaders,
|
Headers: providerHeaders,
|
||||||
Body: providerBody,
|
Body: providerBody,
|
||||||
@@ -198,7 +204,7 @@ func (e *ConversionEngine) CreateStreamConverter(clientProtocol, providerProtoco
|
|||||||
|
|
||||||
ctx := ConversionContext{
|
ctx := ConversionContext{
|
||||||
ConversionID: uuid.New().String(),
|
ConversionID: uuid.New().String(),
|
||||||
InterfaceType: InterfaceTypeChat,
|
InterfaceType: interfaceType,
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,7 +274,7 @@ func (e *ConversionEngine) convertResponseBody(interfaceType InterfaceType, clie
|
|||||||
func (e *ConversionEngine) convertChatBody(clientAdapter, providerAdapter ProtocolAdapter, provider *TargetProvider, body []byte) ([]byte, error) {
|
func (e *ConversionEngine) convertChatBody(clientAdapter, providerAdapter ProtocolAdapter, provider *TargetProvider, body []byte) ([]byte, error) {
|
||||||
canonicalReq, err := clientAdapter.DecodeRequest(body)
|
canonicalReq, err := clientAdapter.DecodeRequest(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, NewConversionError(ErrorCodeJSONParseError, "解码请求失败").WithCause(err)
|
return nil, NewRequestJSONParseError("解码请求失败", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := NewConversionContext(InterfaceTypeChat)
|
ctx := NewConversionContext(InterfaceTypeChat)
|
||||||
@@ -276,6 +282,9 @@ func (e *ConversionEngine) convertChatBody(clientAdapter, providerAdapter Protoc
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if containsUnsupportedMultimodal(canonicalReq) {
|
||||||
|
return nil, NewConversionError(ErrorCodeUnsupportedMultimodal, "跨协议暂不支持多模态内容")
|
||||||
|
}
|
||||||
|
|
||||||
encoded, err := providerAdapter.EncodeRequest(canonicalReq, provider)
|
encoded, err := providerAdapter.EncodeRequest(canonicalReq, provider)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -287,7 +296,7 @@ func (e *ConversionEngine) convertChatBody(clientAdapter, providerAdapter Protoc
|
|||||||
func (e *ConversionEngine) convertChatResponseBody(clientAdapter, providerAdapter ProtocolAdapter, body []byte, modelOverride string) ([]byte, error) {
|
func (e *ConversionEngine) convertChatResponseBody(clientAdapter, providerAdapter ProtocolAdapter, body []byte, modelOverride string) ([]byte, error) {
|
||||||
canonicalResp, err := providerAdapter.DecodeResponse(body)
|
canonicalResp, err := providerAdapter.DecodeResponse(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, NewConversionError(ErrorCodeJSONParseError, "解码响应失败").WithCause(err)
|
return nil, NewResponseJSONParseError("解码响应失败", err)
|
||||||
}
|
}
|
||||||
if modelOverride != "" {
|
if modelOverride != "" {
|
||||||
canonicalResp.Model = modelOverride
|
canonicalResp.Model = modelOverride
|
||||||
@@ -375,6 +384,7 @@ func (e *ConversionEngine) DetectInterfaceType(nativePath, clientProtocol string
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return InterfaceTypePassthrough, err
|
return InterfaceTypePassthrough, err
|
||||||
}
|
}
|
||||||
|
nativePath, _ = splitRequestPath(nativePath)
|
||||||
return adapter.DetectInterfaceType(nativePath), nil
|
return adapter.DetectInterfaceType(nativePath), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -398,3 +408,46 @@ func (e *ConversionEngine) EncodeError(err *ConversionError, clientProtocol stri
|
|||||||
body, statusCode := adapter.EncodeError(err)
|
body, statusCode := adapter.EncodeError(err)
|
||||||
return body, statusCode, nil
|
return body, statusCode, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func splitRequestPath(rawPath string) (string, string) {
|
||||||
|
path, query, found := strings.Cut(rawPath, "?")
|
||||||
|
if !found {
|
||||||
|
return rawPath, ""
|
||||||
|
}
|
||||||
|
return path, query
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendRawQuery(path, rawQuery string) string {
|
||||||
|
if rawQuery == "" {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
if strings.Contains(path, "?") {
|
||||||
|
return path + "&" + rawQuery
|
||||||
|
}
|
||||||
|
return path + "?" + rawQuery
|
||||||
|
}
|
||||||
|
|
||||||
|
func joinBaseURL(baseURL, path string) string {
|
||||||
|
if baseURL == "" {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
if path == "" {
|
||||||
|
return baseURL
|
||||||
|
}
|
||||||
|
return strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(path, "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsUnsupportedMultimodal(req *canonical.CanonicalRequest) bool {
|
||||||
|
if req == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, msg := range req.Messages {
|
||||||
|
for _, block := range msg.Content {
|
||||||
|
switch block.Type {
|
||||||
|
case "image", "audio", "video", "file":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
63
backend/internal/conversion/engine_adapter_test.go
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
package conversion_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"nex/backend/internal/conversion"
|
||||||
|
"nex/backend/internal/conversion/anthropic"
|
||||||
|
"nex/backend/internal/conversion/openai"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConvertHttpRequest_SameProtocolUsesAdapterBuildURL(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
adapter conversion.ProtocolAdapter
|
||||||
|
clientProtocol string
|
||||||
|
providerProtocol string
|
||||||
|
baseURL string
|
||||||
|
nativePath string
|
||||||
|
expectedURL string
|
||||||
|
body []byte
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "openai base url includes version path",
|
||||||
|
adapter: openai.NewAdapter(),
|
||||||
|
clientProtocol: "openai",
|
||||||
|
providerProtocol: "openai",
|
||||||
|
baseURL: "http://example.com/v1",
|
||||||
|
nativePath: "/chat/completions",
|
||||||
|
expectedURL: "http://example.com/v1/chat/completions",
|
||||||
|
body: []byte(`{"model":"gpt-4","messages":[]}`),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "anthropic native path keeps v1",
|
||||||
|
adapter: anthropic.NewAdapter(),
|
||||||
|
clientProtocol: "anthropic",
|
||||||
|
providerProtocol: "anthropic",
|
||||||
|
baseURL: "http://example.com",
|
||||||
|
nativePath: "/v1/messages",
|
||||||
|
expectedURL: "http://example.com/v1/messages",
|
||||||
|
body: []byte(`{"model":"claude","messages":[]}`),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
registry := conversion.NewMemoryRegistry()
|
||||||
|
engine := conversion.NewConversionEngine(registry, zap.NewNop())
|
||||||
|
require.NoError(t, registry.Register(tt.adapter))
|
||||||
|
|
||||||
|
out, err := engine.ConvertHttpRequest(conversion.HTTPRequestSpec{
|
||||||
|
URL: tt.nativePath,
|
||||||
|
Method: "POST",
|
||||||
|
Body: tt.body,
|
||||||
|
}, tt.clientProtocol, tt.providerProtocol, conversion.NewTargetProvider(tt.baseURL, "key", "upstream-model"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, tt.expectedURL, out.URL)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package conversion
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"nex/backend/internal/conversion/canonical"
|
"nex/backend/internal/conversion/canonical"
|
||||||
@@ -287,19 +288,33 @@ func TestDetectInterfaceType_NonExistentProtocol(t *testing.T) {
|
|||||||
func TestConvertHttpRequest_Passthrough(t *testing.T) {
|
func TestConvertHttpRequest_Passthrough(t *testing.T) {
|
||||||
registry := NewMemoryRegistry()
|
registry := NewMemoryRegistry()
|
||||||
engine := NewConversionEngine(registry, zap.NewNop())
|
engine := NewConversionEngine(registry, zap.NewNop())
|
||||||
_ = engine.RegisterAdapter(newMockAdapter("openai", true))
|
openaiAdapter := &buildURLMockAdapter{
|
||||||
|
mockProtocolAdapter: newMockAdapter("openai", true),
|
||||||
|
buildURLFn: func(nativePath string, interfaceType InterfaceType) string {
|
||||||
|
if interfaceType == InterfaceTypeChat {
|
||||||
|
return "/chat/completions"
|
||||||
|
}
|
||||||
|
return nativePath
|
||||||
|
},
|
||||||
|
}
|
||||||
|
openaiAdapter.ifaceType = InterfaceTypeChat
|
||||||
|
openaiAdapter.supportsIface[InterfaceTypeChat] = true
|
||||||
|
openaiAdapter.rewriteReqFn = func(body []byte, newModel string, ifaceType InterfaceType) ([]byte, error) {
|
||||||
|
return []byte(`{"model":"` + newModel + `","messages":[{"role":"user","content":"hi"}]}`), nil
|
||||||
|
}
|
||||||
|
_ = engine.RegisterAdapter(openaiAdapter)
|
||||||
|
|
||||||
provider := NewTargetProvider("https://api.openai.com/v1", "sk-test", "gpt-4")
|
provider := NewTargetProvider("https://api.openai.com/v1", "sk-test", "gpt-4")
|
||||||
spec := HTTPRequestSpec{
|
spec := HTTPRequestSpec{
|
||||||
URL: "/chat/completions",
|
URL: "/v1/chat/completions",
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Body: []byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}`),
|
Body: []byte(`{"model":"openai/gpt-4","messages":[{"role":"user","content":"hi"}]}`),
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := engine.ConvertHttpRequest(spec, "openai", "openai", provider)
|
result, err := engine.ConvertHttpRequest(spec, "openai", "openai", provider)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, "https://api.openai.com/v1/chat/completions", result.URL)
|
assert.Equal(t, "https://api.openai.com/v1/chat/completions", result.URL)
|
||||||
assert.Equal(t, spec.Body, result.Body)
|
assert.JSONEq(t, `{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}`, string(result.Body))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConvertHttpRequest_CrossProtocol(t *testing.T) {
|
func TestConvertHttpRequest_CrossProtocol(t *testing.T) {
|
||||||
@@ -334,6 +349,77 @@ func TestConvertHttpRequest_CrossProtocol(t *testing.T) {
|
|||||||
assert.NotNil(t, result.Body)
|
assert.NotNil(t, result.Body)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestConvertHttpRequest_UsesProviderAdapterBuildURL(t *testing.T) {
|
||||||
|
registry := NewMemoryRegistry()
|
||||||
|
engine := NewConversionEngine(registry, zap.NewNop())
|
||||||
|
openaiAdapter := &buildURLMockAdapter{
|
||||||
|
mockProtocolAdapter: newMockAdapter("openai", true),
|
||||||
|
buildURLFn: func(nativePath string, interfaceType InterfaceType) string {
|
||||||
|
if interfaceType == InterfaceTypeChat {
|
||||||
|
return "/chat/completions"
|
||||||
|
}
|
||||||
|
return nativePath
|
||||||
|
},
|
||||||
|
}
|
||||||
|
openaiAdapter.ifaceType = InterfaceTypeChat
|
||||||
|
openaiAdapter.supportsIface[InterfaceTypeChat] = true
|
||||||
|
openaiAdapter.rewriteReqFn = func(body []byte, newModel string, ifaceType InterfaceType) ([]byte, error) {
|
||||||
|
return []byte(`{"model":"` + newModel + `"}`), nil
|
||||||
|
}
|
||||||
|
require.NoError(t, registry.Register(openaiAdapter))
|
||||||
|
|
||||||
|
anthropicAdapter := &buildURLMockAdapter{
|
||||||
|
mockProtocolAdapter: newMockAdapter("anthropic", false),
|
||||||
|
buildURLFn: func(nativePath string, interfaceType InterfaceType) string {
|
||||||
|
if interfaceType == InterfaceTypeChat {
|
||||||
|
return "/v1/messages"
|
||||||
|
}
|
||||||
|
return nativePath
|
||||||
|
},
|
||||||
|
}
|
||||||
|
anthropicAdapter.ifaceType = InterfaceTypeChat
|
||||||
|
anthropicAdapter.supportsIface[InterfaceTypeChat] = true
|
||||||
|
require.NoError(t, registry.Register(anthropicAdapter))
|
||||||
|
|
||||||
|
t.Run("OpenAI to Anthropic", func(t *testing.T) {
|
||||||
|
provider := NewTargetProvider("https://api.anthropic.com", "key", "claude-3")
|
||||||
|
spec := HTTPRequestSpec{
|
||||||
|
URL: "/v1/chat/completions",
|
||||||
|
Method: "POST",
|
||||||
|
Body: []byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}],"max_tokens":16}`),
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := engine.ConvertHttpRequest(spec, "openai", "anthropic", provider)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "https://api.anthropic.com/v1/messages", result.URL)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Anthropic to OpenAI", func(t *testing.T) {
|
||||||
|
provider := NewTargetProvider("https://api.openai.com/v1", "key", "gpt-4")
|
||||||
|
spec := HTTPRequestSpec{
|
||||||
|
URL: "/v1/messages",
|
||||||
|
Method: "POST",
|
||||||
|
Body: []byte(`{"model":"p1/claude-3","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`),
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := engine.ConvertHttpRequest(spec, "anthropic", "openai", provider)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "https://api.openai.com/v1/chat/completions", result.URL)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type buildURLMockAdapter struct {
|
||||||
|
*mockProtocolAdapter
|
||||||
|
buildURLFn func(string, InterfaceType) string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *buildURLMockAdapter) BuildUrl(nativePath string, interfaceType InterfaceType) string {
|
||||||
|
if m.buildURLFn != nil {
|
||||||
|
return m.buildURLFn(nativePath, interfaceType)
|
||||||
|
}
|
||||||
|
return m.mockProtocolAdapter.BuildUrl(nativePath, interfaceType)
|
||||||
|
}
|
||||||
|
|
||||||
func TestConvertHttpResponse_Passthrough(t *testing.T) {
|
func TestConvertHttpResponse_Passthrough(t *testing.T) {
|
||||||
registry := NewMemoryRegistry()
|
registry := NewMemoryRegistry()
|
||||||
engine := NewConversionEngine(registry, zap.NewNop())
|
engine := NewConversionEngine(registry, zap.NewNop())
|
||||||
@@ -498,12 +584,13 @@ func TestCreateStreamConverter_ModelOverride_SmartPassthrough(t *testing.T) {
|
|||||||
_, ok := converter.(*SmartPassthroughStreamConverter)
|
_, ok := converter.(*SmartPassthroughStreamConverter)
|
||||||
assert.True(t, ok)
|
assert.True(t, ok)
|
||||||
|
|
||||||
// 验证 chunk 改写
|
// 验证 SSE frame 中的 data JSON 被改写
|
||||||
chunks := converter.ProcessChunk([]byte(`{"model":"gpt-4","choices":[]}`))
|
chunks := converter.ProcessChunk([]byte(`data: {"model":"gpt-4","choices":[]}` + "\n\n"))
|
||||||
require.Len(t, chunks, 1)
|
require.Len(t, chunks, 1)
|
||||||
|
|
||||||
var resp map[string]interface{}
|
var resp map[string]interface{}
|
||||||
require.NoError(t, json.Unmarshal(chunks[0], &resp))
|
payload := strings.TrimPrefix(strings.TrimSpace(string(chunks[0])), "data: ")
|
||||||
|
require.NoError(t, json.Unmarshal([]byte(payload), &resp))
|
||||||
assert.Equal(t, "openai/gpt-4", resp["model"])
|
assert.Equal(t, "openai/gpt-4", resp["model"])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,13 @@ const (
|
|||||||
ErrorCodeProtocolConstraint ErrorCode = "PROTOCOL_CONSTRAINT_VIOLATION"
|
ErrorCodeProtocolConstraint ErrorCode = "PROTOCOL_CONSTRAINT_VIOLATION"
|
||||||
ErrorCodeEncodingFailure ErrorCode = "ENCODING_FAILURE"
|
ErrorCodeEncodingFailure ErrorCode = "ENCODING_FAILURE"
|
||||||
ErrorCodeInterfaceNotSupported ErrorCode = "INTERFACE_NOT_SUPPORTED"
|
ErrorCodeInterfaceNotSupported ErrorCode = "INTERFACE_NOT_SUPPORTED"
|
||||||
|
ErrorCodeUnsupportedMultimodal ErrorCode = "UNSUPPORTED_MULTIMODAL"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ErrorDetailPhase = "phase"
|
||||||
|
ErrorPhaseRequest = "request"
|
||||||
|
ErrorPhaseResponse = "response"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConversionError 协议转换错误
|
// ConversionError 协议转换错误
|
||||||
@@ -39,6 +46,20 @@ func NewConversionError(code ErrorCode, message string) *ConversionError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewRequestJSONParseError 创建请求 JSON 解析错误。
|
||||||
|
func NewRequestJSONParseError(message string, cause error) *ConversionError {
|
||||||
|
return NewConversionError(ErrorCodeJSONParseError, message).
|
||||||
|
WithDetail(ErrorDetailPhase, ErrorPhaseRequest).
|
||||||
|
WithCause(cause)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewResponseJSONParseError 创建响应 JSON 解析错误。
|
||||||
|
func NewResponseJSONParseError(message string, cause error) *ConversionError {
|
||||||
|
return NewConversionError(ErrorCodeJSONParseError, message).
|
||||||
|
WithDetail(ErrorDetailPhase, ErrorPhaseResponse).
|
||||||
|
WithCause(cause)
|
||||||
|
}
|
||||||
|
|
||||||
// WithClientProtocol 设置客户端协议
|
// WithClientProtocol 设置客户端协议
|
||||||
func (e *ConversionError) WithClientProtocol(protocol string) *ConversionError {
|
func (e *ConversionError) WithClientProtocol(protocol string) *ConversionError {
|
||||||
e.ClientProtocol = protocol
|
e.ClientProtocol = protocol
|
||||||
|
|||||||
@@ -29,27 +29,27 @@ func (a *Adapter) SupportsPassthrough() bool { return true }
|
|||||||
// DetectInterfaceType 根据路径检测接口类型
|
// DetectInterfaceType 根据路径检测接口类型
|
||||||
func (a *Adapter) DetectInterfaceType(nativePath string) conversion.InterfaceType {
|
func (a *Adapter) DetectInterfaceType(nativePath string) conversion.InterfaceType {
|
||||||
switch {
|
switch {
|
||||||
case nativePath == "/chat/completions":
|
case nativePath == "/v1/chat/completions":
|
||||||
return conversion.InterfaceTypeChat
|
return conversion.InterfaceTypeChat
|
||||||
case nativePath == "/models":
|
case nativePath == "/v1/models":
|
||||||
return conversion.InterfaceTypeModels
|
return conversion.InterfaceTypeModels
|
||||||
case isModelInfoPath(nativePath):
|
case isModelInfoPath(nativePath):
|
||||||
return conversion.InterfaceTypeModelInfo
|
return conversion.InterfaceTypeModelInfo
|
||||||
case nativePath == "/embeddings":
|
case nativePath == "/v1/embeddings":
|
||||||
return conversion.InterfaceTypeEmbeddings
|
return conversion.InterfaceTypeEmbeddings
|
||||||
case nativePath == "/rerank":
|
case nativePath == "/v1/rerank":
|
||||||
return conversion.InterfaceTypeRerank
|
return conversion.InterfaceTypeRerank
|
||||||
default:
|
default:
|
||||||
return conversion.InterfaceTypePassthrough
|
return conversion.InterfaceTypePassthrough
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// isModelInfoPath 判断是否为模型详情路径(/models/{id},允许 id 含 /)
|
// isModelInfoPath 判断是否为模型详情路径(/v1/models/{id},允许 id 含 /)
|
||||||
func isModelInfoPath(path string) bool {
|
func isModelInfoPath(path string) bool {
|
||||||
if !strings.HasPrefix(path, "/models/") {
|
if !strings.HasPrefix(path, "/v1/models/") {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
suffix := path[len("/models/"):]
|
suffix := path[len("/v1/models/"):]
|
||||||
return suffix != ""
|
return suffix != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,6 +60,11 @@ func (a *Adapter) BuildUrl(nativePath string, interfaceType conversion.Interface
|
|||||||
return "/chat/completions"
|
return "/chat/completions"
|
||||||
case conversion.InterfaceTypeModels:
|
case conversion.InterfaceTypeModels:
|
||||||
return "/models"
|
return "/models"
|
||||||
|
case conversion.InterfaceTypeModelInfo:
|
||||||
|
if modelID, err := a.ExtractUnifiedModelID(nativePath); err == nil {
|
||||||
|
return "/models/" + modelID
|
||||||
|
}
|
||||||
|
return nativePath
|
||||||
case conversion.InterfaceTypeEmbeddings:
|
case conversion.InterfaceTypeEmbeddings:
|
||||||
return "/embeddings"
|
return "/embeddings"
|
||||||
case conversion.InterfaceTypeRerank:
|
case conversion.InterfaceTypeRerank:
|
||||||
@@ -221,12 +226,12 @@ func (a *Adapter) EncodeRerankResponse(resp *canonical.CanonicalRerankResponse)
|
|||||||
return encodeRerankResponse(resp)
|
return encodeRerankResponse(resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExtractUnifiedModelID 从路径中提取统一模型 ID(/models/{provider_id}/{model_name})
|
// ExtractUnifiedModelID 从路径中提取统一模型 ID(/v1/models/{provider_id}/{model_name})
|
||||||
func (a *Adapter) ExtractUnifiedModelID(nativePath string) (string, error) {
|
func (a *Adapter) ExtractUnifiedModelID(nativePath string) (string, error) {
|
||||||
if !strings.HasPrefix(nativePath, "/models/") {
|
if !strings.HasPrefix(nativePath, "/v1/models/") {
|
||||||
return "", fmt.Errorf("不是模型详情路径: %s", nativePath)
|
return "", fmt.Errorf("不是模型详情路径: %s", nativePath)
|
||||||
}
|
}
|
||||||
suffix := nativePath[len("/models/"):]
|
suffix := nativePath[len("/v1/models/"):]
|
||||||
if suffix == "" {
|
if suffix == "" {
|
||||||
return "", fmt.Errorf("路径缺少模型 ID")
|
return "", fmt.Errorf("路径缺少模型 ID")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,11 +28,11 @@ func TestAdapter_DetectInterfaceType(t *testing.T) {
|
|||||||
path string
|
path string
|
||||||
expected conversion.InterfaceType
|
expected conversion.InterfaceType
|
||||||
}{
|
}{
|
||||||
{"聊天补全", "/chat/completions", conversion.InterfaceTypeChat},
|
{"聊天补全", "/v1/chat/completions", conversion.InterfaceTypeChat},
|
||||||
{"模型列表", "/models", conversion.InterfaceTypeModels},
|
{"模型列表", "/v1/models", conversion.InterfaceTypeModels},
|
||||||
{"模型详情", "/models/gpt-4", conversion.InterfaceTypeModelInfo},
|
{"模型详情", "/v1/models/openai/gpt-4", conversion.InterfaceTypeModelInfo},
|
||||||
{"嵌入接口", "/embeddings", conversion.InterfaceTypeEmbeddings},
|
{"嵌入接口", "/v1/embeddings", conversion.InterfaceTypeEmbeddings},
|
||||||
{"重排序接口", "/rerank", conversion.InterfaceTypeRerank},
|
{"重排序接口", "/v1/rerank", conversion.InterfaceTypeRerank},
|
||||||
{"未知路径", "/unknown", conversion.InterfaceTypePassthrough},
|
{"未知路径", "/unknown", conversion.InterfaceTypePassthrough},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,6 +44,27 @@ func TestAdapter_DetectInterfaceType(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdapter_OldPathsBecomePassthrough(t *testing.T) {
|
||||||
|
a := NewAdapter()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
path string
|
||||||
|
expected conversion.InterfaceType
|
||||||
|
}{
|
||||||
|
{"/chat/completions", conversion.InterfaceTypePassthrough},
|
||||||
|
{"/models", conversion.InterfaceTypePassthrough},
|
||||||
|
{"/models/gpt-4.1", conversion.InterfaceTypePassthrough},
|
||||||
|
{"/embeddings", conversion.InterfaceTypePassthrough},
|
||||||
|
{"/rerank", conversion.InterfaceTypePassthrough},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.path, func(t *testing.T) {
|
||||||
|
assert.Equal(t, tt.expected, a.DetectInterfaceType(tt.path))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAdapter_BuildUrl(t *testing.T) {
|
func TestAdapter_BuildUrl(t *testing.T) {
|
||||||
a := NewAdapter()
|
a := NewAdapter()
|
||||||
|
|
||||||
@@ -53,10 +74,12 @@ func TestAdapter_BuildUrl(t *testing.T) {
|
|||||||
interfaceType conversion.InterfaceType
|
interfaceType conversion.InterfaceType
|
||||||
expected string
|
expected string
|
||||||
}{
|
}{
|
||||||
{"聊天", "/chat/completions", conversion.InterfaceTypeChat, "/chat/completions"},
|
{"聊天", "/v1/chat/completions", conversion.InterfaceTypeChat, "/chat/completions"},
|
||||||
{"模型", "/models", conversion.InterfaceTypeModels, "/models"},
|
{"模型", "/v1/models", conversion.InterfaceTypeModels, "/models"},
|
||||||
{"嵌入", "/embeddings", conversion.InterfaceTypeEmbeddings, "/embeddings"},
|
{"模型详情", "/v1/models/openai/gpt-4", conversion.InterfaceTypeModelInfo, "/models/openai/gpt-4"},
|
||||||
{"重排序", "/rerank", conversion.InterfaceTypeRerank, "/rerank"},
|
{"复杂模型详情", "/v1/models/azure/accounts/org/models/gpt-4", conversion.InterfaceTypeModelInfo, "/models/azure/accounts/org/models/gpt-4"},
|
||||||
|
{"嵌入", "/v1/embeddings", conversion.InterfaceTypeEmbeddings, "/embeddings"},
|
||||||
|
{"重排序", "/v1/rerank", conversion.InterfaceTypeRerank, "/rerank"},
|
||||||
{"默认透传", "/other", conversion.InterfaceTypePassthrough, "/other"},
|
{"默认透传", "/other", conversion.InterfaceTypePassthrough, "/other"},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,12 +141,12 @@ func TestIsModelInfoPath(t *testing.T) {
|
|||||||
path string
|
path string
|
||||||
expected bool
|
expected bool
|
||||||
}{
|
}{
|
||||||
{"model_info", "/models/gpt-4", true},
|
{"model_info", "/v1/models/openai/gpt-4", true},
|
||||||
{"model_info_with_dots", "/models/gpt-4.1-preview", true},
|
{"model_info_with_dots", "/v1/models/openai/gpt-4.1-preview", true},
|
||||||
{"models_list", "/models", false},
|
{"models_list", "/v1/models", false},
|
||||||
{"nested_path", "/models/gpt-4/versions", true},
|
{"nested_path", "/v1/models/azure/accounts/org-123/models/gpt-4", true},
|
||||||
{"empty_suffix", "/models/", false},
|
{"empty_suffix", "/v1/models/", false},
|
||||||
{"unrelated", "/chat/completions", false},
|
{"unrelated", "/v1/chat/completions", false},
|
||||||
{"partial_prefix", "/model", false},
|
{"partial_prefix", "/model", false},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +157,27 @@ func TestIsModelInfoPath(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdapter_ExtractUnifiedModelID(t *testing.T) {
|
||||||
|
a := NewAdapter()
|
||||||
|
|
||||||
|
t.Run("标准路径", func(t *testing.T) {
|
||||||
|
modelID, err := a.ExtractUnifiedModelID("/v1/models/openai/gpt-4")
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "openai/gpt-4", modelID)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("复杂路径", func(t *testing.T) {
|
||||||
|
modelID, err := a.ExtractUnifiedModelID("/v1/models/azure/accounts/org/models/gpt-4")
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "azure/accounts/org/models/gpt-4", modelID)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("非模型详情路径报错", func(t *testing.T) {
|
||||||
|
_, err := a.ExtractUnifiedModelID("/v1/models")
|
||||||
|
require.Error(t, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func TestAdapter_EncodeError_InvalidInput(t *testing.T) {
|
func TestAdapter_EncodeError_InvalidInput(t *testing.T) {
|
||||||
a := NewAdapter()
|
a := NewAdapter()
|
||||||
convErr := conversion.NewConversionError(conversion.ErrorCodeInvalidInput, "参数无效")
|
convErr := conversion.NewConversionError(conversion.ErrorCodeInvalidInput, "参数无效")
|
||||||
|
|||||||
@@ -18,35 +18,35 @@ func TestExtractUnifiedModelID(t *testing.T) {
|
|||||||
a := NewAdapter()
|
a := NewAdapter()
|
||||||
|
|
||||||
t.Run("standard_path", func(t *testing.T) {
|
t.Run("standard_path", func(t *testing.T) {
|
||||||
id, err := a.ExtractUnifiedModelID("/models/openai/gpt-4")
|
id, err := a.ExtractUnifiedModelID("/v1/models/openai/gpt-4")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, "openai/gpt-4", id)
|
assert.Equal(t, "openai/gpt-4", id)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("multi_segment_path", func(t *testing.T) {
|
t.Run("multi_segment_path", func(t *testing.T) {
|
||||||
id, err := a.ExtractUnifiedModelID("/models/azure/accounts/org/models/gpt-4")
|
id, err := a.ExtractUnifiedModelID("/v1/models/azure/accounts/org/models/gpt-4")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, "azure/accounts/org/models/gpt-4", id)
|
assert.Equal(t, "azure/accounts/org/models/gpt-4", id)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("single_segment", func(t *testing.T) {
|
t.Run("single_segment", func(t *testing.T) {
|
||||||
id, err := a.ExtractUnifiedModelID("/models/gpt-4")
|
id, err := a.ExtractUnifiedModelID("/v1/models/gpt-4")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, "gpt-4", id)
|
assert.Equal(t, "gpt-4", id)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("non_model_path", func(t *testing.T) {
|
t.Run("non_model_path", func(t *testing.T) {
|
||||||
_, err := a.ExtractUnifiedModelID("/chat/completions")
|
_, err := a.ExtractUnifiedModelID("/v1/chat/completions")
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("empty_suffix", func(t *testing.T) {
|
t.Run("empty_suffix", func(t *testing.T) {
|
||||||
_, err := a.ExtractUnifiedModelID("/models/")
|
_, err := a.ExtractUnifiedModelID("/v1/models/")
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("models_list_no_slash", func(t *testing.T) {
|
t.Run("models_list_no_slash", func(t *testing.T) {
|
||||||
_, err := a.ExtractUnifiedModelID("/models")
|
_, err := a.ExtractUnifiedModelID("/v1/models")
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -344,12 +344,12 @@ func TestIsModelInfoPath_UnifiedModelID(t *testing.T) {
|
|||||||
path string
|
path string
|
||||||
expected bool
|
expected bool
|
||||||
}{
|
}{
|
||||||
{"simple_model_id", "/models/gpt-4", true},
|
{"simple_model_id", "/v1/models/gpt-4", true},
|
||||||
{"unified_model_id_with_slash", "/models/openai/gpt-4", true},
|
{"unified_model_id_with_slash", "/v1/models/openai/gpt-4", true},
|
||||||
{"models_list", "/models", false},
|
{"models_list", "/v1/models", false},
|
||||||
{"models_list_trailing_slash", "/models/", false},
|
{"models_list_trailing_slash", "/v1/models/", false},
|
||||||
{"chat_completions", "/chat/completions", false},
|
{"chat_completions", "/v1/chat/completions", false},
|
||||||
{"deeply_nested", "/models/azure/eastus/deployments/my-dept/models/gpt-4", true},
|
{"deeply_nested", "/v1/models/azure/eastus/deployments/my-dept/models/gpt-4", true},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
package conversion
|
package conversion
|
||||||
|
|
||||||
import "nex/backend/internal/conversion/canonical"
|
import (
|
||||||
|
"bytes"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"nex/backend/internal/conversion/canonical"
|
||||||
|
)
|
||||||
|
|
||||||
// StreamDecoder 流式解码器接口
|
// StreamDecoder 流式解码器接口
|
||||||
type StreamDecoder interface {
|
type StreamDecoder interface {
|
||||||
@@ -39,11 +44,12 @@ func (c *PassthroughStreamConverter) Flush() [][]byte {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SmartPassthroughStreamConverter 同协议 Smart Passthrough 流式转换器
|
// SmartPassthroughStreamConverter 同协议 Smart Passthrough 流式转换器
|
||||||
// 逐 chunk 改写 model 字段
|
// 按 SSE frame 改写 data JSON 中的 model 字段
|
||||||
type SmartPassthroughStreamConverter struct {
|
type SmartPassthroughStreamConverter struct {
|
||||||
adapter ProtocolAdapter
|
adapter ProtocolAdapter
|
||||||
modelOverride string
|
modelOverride string
|
||||||
interfaceType InterfaceType
|
interfaceType InterfaceType
|
||||||
|
buffer []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewSmartPassthroughStreamConverter 创建 Smart Passthrough 流式转换器
|
// NewSmartPassthroughStreamConverter 创建 Smart Passthrough 流式转换器
|
||||||
@@ -55,25 +61,46 @@ func NewSmartPassthroughStreamConverter(adapter ProtocolAdapter, modelOverride s
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProcessChunk 改写 chunk 中的 model 字段
|
// ProcessChunk 按 SSE frame 改写 data JSON 中的 model 字段
|
||||||
func (c *SmartPassthroughStreamConverter) ProcessChunk(rawChunk []byte) [][]byte {
|
func (c *SmartPassthroughStreamConverter) ProcessChunk(rawChunk []byte) [][]byte {
|
||||||
if len(rawChunk) == 0 {
|
if len(rawChunk) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
rewrittenChunk, err := c.adapter.RewriteResponseModelName(rawChunk, c.modelOverride, c.interfaceType)
|
c.buffer = append(c.buffer, rawChunk...)
|
||||||
|
frames, rest := splitSSEFrames(c.buffer)
|
||||||
|
c.buffer = rest
|
||||||
|
|
||||||
|
result := make([][]byte, 0, len(frames))
|
||||||
|
for _, frame := range frames {
|
||||||
|
result = append(result, c.rewriteFrame(frame))
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *SmartPassthroughStreamConverter) rewriteFrame(frame []byte) []byte {
|
||||||
|
payload, ok := sseFrameDataPayload(frame)
|
||||||
|
if !ok || strings.TrimSpace(payload) == "[DONE]" {
|
||||||
|
return frame
|
||||||
|
}
|
||||||
|
|
||||||
|
rewrittenPayload, err := c.adapter.RewriteResponseModelName([]byte(payload), c.modelOverride, c.interfaceType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// 改写失败,返回原始 chunk
|
return frame
|
||||||
return [][]byte{rawChunk}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return [][]byte{rewrittenChunk}
|
return rebuildSSEFrameWithData(frame, string(rewrittenPayload))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Flush 无缓冲数据
|
// Flush 输出未形成完整 frame 的剩余数据
|
||||||
func (c *SmartPassthroughStreamConverter) Flush() [][]byte {
|
func (c *SmartPassthroughStreamConverter) Flush() [][]byte {
|
||||||
|
if len(c.buffer) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
frame := append([]byte(nil), c.buffer...)
|
||||||
|
c.buffer = nil
|
||||||
|
return [][]byte{c.rewriteFrame(frame)}
|
||||||
|
}
|
||||||
|
|
||||||
// CanonicalStreamConverter 跨协议规范流式转换器
|
// CanonicalStreamConverter 跨协议规范流式转换器
|
||||||
type CanonicalStreamConverter struct {
|
type CanonicalStreamConverter struct {
|
||||||
@@ -153,3 +180,86 @@ func (c *CanonicalStreamConverter) applyModelOverride(event *canonical.Canonical
|
|||||||
event.Message.Model = c.modelOverride
|
event.Message.Model = c.modelOverride
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func splitSSEFrames(data []byte) ([][]byte, []byte) {
|
||||||
|
var frames [][]byte
|
||||||
|
for len(data) > 0 {
|
||||||
|
idx, sepLen := findSSEFrameSeparator(data)
|
||||||
|
if idx < 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
end := idx + sepLen
|
||||||
|
frames = append(frames, append([]byte(nil), data[:end]...))
|
||||||
|
data = data[end:]
|
||||||
|
}
|
||||||
|
return frames, data
|
||||||
|
}
|
||||||
|
|
||||||
|
func findSSEFrameSeparator(data []byte) (int, int) {
|
||||||
|
lf := bytes.Index(data, []byte("\n\n"))
|
||||||
|
crlf := bytes.Index(data, []byte("\r\n\r\n"))
|
||||||
|
switch {
|
||||||
|
case lf < 0 && crlf < 0:
|
||||||
|
return -1, 0
|
||||||
|
case lf < 0:
|
||||||
|
return crlf, 4
|
||||||
|
case crlf < 0:
|
||||||
|
return lf, 2
|
||||||
|
case crlf <= lf:
|
||||||
|
return crlf, 4
|
||||||
|
default:
|
||||||
|
return lf, 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sseFrameDataPayload(frame []byte) (string, bool) {
|
||||||
|
text := strings.TrimRight(string(frame), "\r\n")
|
||||||
|
lines := strings.Split(text, "\n")
|
||||||
|
var dataLines []string
|
||||||
|
for _, line := range lines {
|
||||||
|
line = strings.TrimRight(line, "\r")
|
||||||
|
if strings.HasPrefix(line, "data:") {
|
||||||
|
value := strings.TrimPrefix(line, "data:")
|
||||||
|
if strings.HasPrefix(value, " ") {
|
||||||
|
value = value[1:]
|
||||||
|
}
|
||||||
|
dataLines = append(dataLines, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(dataLines) == 0 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return strings.Join(dataLines, "\n"), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func rebuildSSEFrameWithData(frame []byte, data string) []byte {
|
||||||
|
lineEnding, separator := sseLineEnding(frame)
|
||||||
|
text := strings.TrimRight(string(frame), "\r\n")
|
||||||
|
lines := strings.Split(text, "\n")
|
||||||
|
out := make([]string, 0, len(lines)+1)
|
||||||
|
dataWritten := false
|
||||||
|
for _, line := range lines {
|
||||||
|
line = strings.TrimRight(line, "\r")
|
||||||
|
if strings.HasPrefix(line, "data:") {
|
||||||
|
if !dataWritten {
|
||||||
|
for _, dataLine := range strings.Split(data, "\n") {
|
||||||
|
out = append(out, "data: "+dataLine)
|
||||||
|
}
|
||||||
|
dataWritten = true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, line)
|
||||||
|
}
|
||||||
|
if !dataWritten {
|
||||||
|
out = append(out, "data: "+data)
|
||||||
|
}
|
||||||
|
return []byte(strings.Join(out, lineEnding) + separator)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sseLineEnding(frame []byte) (string, string) {
|
||||||
|
if bytes.Contains(frame, []byte("\r\n")) {
|
||||||
|
return "\r\n", "\r\n\r\n"
|
||||||
|
}
|
||||||
|
return "\n", "\n\n"
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ func Logging(logger *zap.Logger) gin.HandlerFunc {
|
|||||||
if id, ok := requestID.(string); ok {
|
if id, ok := requestID.(string); ok {
|
||||||
requestIDStr = id
|
requestIDStr = id
|
||||||
}
|
}
|
||||||
logger.Info("请求开始",
|
logger.Debug("请求开始",
|
||||||
pkglogger.Method(c.Request.Method),
|
pkglogger.Method(c.Request.Method),
|
||||||
pkglogger.Path(path),
|
pkglogger.Path(path),
|
||||||
pkglogger.Query(query),
|
pkglogger.Query(query),
|
||||||
@@ -33,7 +33,7 @@ func Logging(logger *zap.Logger) gin.HandlerFunc {
|
|||||||
latency := time.Since(start)
|
latency := time.Since(start)
|
||||||
statusCode := c.Writer.Status()
|
statusCode := c.Writer.Status()
|
||||||
|
|
||||||
logger.Info("请求结束",
|
logger.Debug("请求结束",
|
||||||
pkglogger.StatusCode(statusCode),
|
pkglogger.StatusCode(statusCode),
|
||||||
pkglogger.Method(c.Request.Method),
|
pkglogger.Method(c.Request.Method),
|
||||||
pkglogger.Path(path),
|
pkglogger.Path(path),
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
|
"go.uber.org/zap/zapcore"
|
||||||
|
"go.uber.org/zap/zaptest/observer"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
@@ -65,6 +67,61 @@ func TestLogging(t *testing.T) {
|
|||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLogging_DoesNotLogLifecycleAtInfoLevel(t *testing.T) {
|
||||||
|
core, logs := observer.New(zapcore.InfoLevel)
|
||||||
|
logger := zap.New(core)
|
||||||
|
|
||||||
|
w := serveLoggingRequest(logger)
|
||||||
|
|
||||||
|
assert.Equal(t, 200, w.Code)
|
||||||
|
assert.Empty(t, logs.FilterMessage("请求开始").All())
|
||||||
|
assert.Empty(t, logs.FilterMessage("请求结束").All())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogging_LogsLifecycleAtDebugLevel(t *testing.T) {
|
||||||
|
core, logs := observer.New(zapcore.DebugLevel)
|
||||||
|
logger := zap.New(core)
|
||||||
|
|
||||||
|
w := serveLoggingRequest(logger)
|
||||||
|
|
||||||
|
assert.Equal(t, 200, w.Code)
|
||||||
|
startLogs := logs.FilterMessage("请求开始").All()
|
||||||
|
endLogs := logs.FilterMessage("请求结束").All()
|
||||||
|
if assert.Len(t, startLogs, 1) {
|
||||||
|
fields := startLogs[0].ContextMap()
|
||||||
|
assert.Equal(t, "GET", fields["method"])
|
||||||
|
assert.Equal(t, "/test", fields["path"])
|
||||||
|
assert.Equal(t, "key=value", fields["query"])
|
||||||
|
assert.Equal(t, "existing-id-123", fields["request_id"])
|
||||||
|
assert.NotEmpty(t, fields["client_ip"])
|
||||||
|
}
|
||||||
|
if assert.Len(t, endLogs, 1) {
|
||||||
|
fields := endLogs[0].ContextMap()
|
||||||
|
assert.Equal(t, int64(200), fields["status"])
|
||||||
|
assert.Equal(t, "GET", fields["method"])
|
||||||
|
assert.Equal(t, "/test", fields["path"])
|
||||||
|
assert.Equal(t, int64(2), fields["body_size"])
|
||||||
|
assert.Equal(t, "existing-id-123", fields["request_id"])
|
||||||
|
assert.Contains(t, fields, "latency")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveLoggingRequest(logger *zap.Logger) *httptest.ResponseRecorder {
|
||||||
|
r := gin.New()
|
||||||
|
r.Use(RequestID())
|
||||||
|
r.Use(Logging(logger))
|
||||||
|
r.GET("/test", func(c *gin.Context) {
|
||||||
|
c.String(200, "ok")
|
||||||
|
})
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest("GET", "/test?key=value", nil)
|
||||||
|
req.Header.Set("X-Request-ID", "existing-id-123")
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
|
||||||
func TestRecovery_NoPanic(t *testing.T) {
|
func TestRecovery_NoPanic(t *testing.T) {
|
||||||
logger := zap.NewNop()
|
logger := zap.NewNop()
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"nex/backend/internal/domain"
|
"nex/backend/internal/domain"
|
||||||
"nex/backend/internal/provider"
|
"nex/backend/internal/provider"
|
||||||
"nex/backend/internal/service"
|
"nex/backend/internal/service"
|
||||||
|
appErrors "nex/backend/pkg/errors"
|
||||||
"nex/backend/pkg/modelid"
|
"nex/backend/pkg/modelid"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -48,7 +49,7 @@ func (h *ProxyHandler) HandleProxy(c *gin.Context) {
|
|||||||
// 从 URL 提取 clientProtocol: /{protocol}/v1/...
|
// 从 URL 提取 clientProtocol: /{protocol}/v1/...
|
||||||
clientProtocol := c.Param("protocol")
|
clientProtocol := c.Param("protocol")
|
||||||
if clientProtocol == "" {
|
if clientProtocol == "" {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少协议前缀"})
|
h.writeProxyError(c, http.StatusBadRequest, "INVALID_REQUEST", "缺少协议前缀")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,12 +59,13 @@ func (h *ProxyHandler) HandleProxy(c *gin.Context) {
|
|||||||
path = "/" + path
|
path = "/" + path
|
||||||
}
|
}
|
||||||
nativePath := path
|
nativePath := path
|
||||||
|
requestPath := appendRawQuery(nativePath, c.Request.URL.RawQuery)
|
||||||
|
|
||||||
// 获取 client adapter
|
// 获取 client adapter
|
||||||
registry := h.engine.GetRegistry()
|
registry := h.engine.GetRegistry()
|
||||||
clientAdapter, err := registry.Get(clientProtocol)
|
clientAdapter, err := registry.Get(clientProtocol)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的协议: " + clientProtocol})
|
h.writeProxyError(c, http.StatusNotFound, "UNSUPPORTED_INTERFACE", "不支持的协议: "+clientProtocol)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +82,7 @@ func (h *ProxyHandler) HandleProxy(c *gin.Context) {
|
|||||||
if ifaceType == conversion.InterfaceTypeModelInfo {
|
if ifaceType == conversion.InterfaceTypeModelInfo {
|
||||||
unifiedID, err := clientAdapter.ExtractUnifiedModelID(nativePath)
|
unifiedID, err := clientAdapter.ExtractUnifiedModelID(nativePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的模型 ID 格式"})
|
h.writeProxyError(c, http.StatusBadRequest, "INVALID_MODEL_ID", "无效的模型 ID 格式")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.handleModelInfo(c, unifiedID, clientAdapter)
|
h.handleModelInfo(c, unifiedID, clientAdapter)
|
||||||
@@ -90,40 +92,50 @@ func (h *ProxyHandler) HandleProxy(c *gin.Context) {
|
|||||||
// 读取请求体
|
// 读取请求体
|
||||||
body, err := io.ReadAll(c.Request.Body)
|
body, err := io.ReadAll(c.Request.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "读取请求体失败"})
|
h.writeProxyError(c, http.StatusBadRequest, "INVALID_REQUEST", "读取请求体失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析统一模型 ID(使用 adapter.ExtractModelName)
|
|
||||||
var providerID, modelName string
|
|
||||||
if len(body) > 0 {
|
|
||||||
unifiedID, err := clientAdapter.ExtractModelName(body, ifaceType)
|
|
||||||
if err == nil && unifiedID != "" {
|
|
||||||
pid, mn, err := modelid.ParseUnifiedModelID(unifiedID)
|
|
||||||
if err == nil {
|
|
||||||
providerID = pid
|
|
||||||
modelName = mn
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建输入 HTTPRequestSpec
|
// 构建输入 HTTPRequestSpec
|
||||||
inSpec := conversion.HTTPRequestSpec{
|
inSpec := conversion.HTTPRequestSpec{
|
||||||
URL: nativePath,
|
URL: requestPath,
|
||||||
Method: c.Request.Method,
|
Method: c.Request.Method,
|
||||||
Headers: extractHeaders(c),
|
Headers: extractHeaders(c),
|
||||||
Body: body,
|
Body: body,
|
||||||
}
|
}
|
||||||
|
isStream := h.isStreamRequest(body, clientProtocol, nativePath)
|
||||||
|
|
||||||
|
// 只有 adapter 明确适配的接口才提取 model。未知接口不做通用 model 猜测。
|
||||||
|
if len(body) == 0 || !supportsModelExtraction(ifaceType) {
|
||||||
|
h.forwardPassthrough(c, inSpec, clientProtocol, ifaceType, isStream)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
unifiedID, err := clientAdapter.ExtractModelName(body, ifaceType)
|
||||||
|
if err != nil {
|
||||||
|
if isInvalidJSONError(err) {
|
||||||
|
h.writeProxyError(c, http.StatusBadRequest, "INVALID_JSON", "请求体 JSON 格式错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.forwardPassthrough(c, inSpec, clientProtocol, ifaceType, isStream)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
providerID, modelName, err := modelid.ParseUnifiedModelID(unifiedID)
|
||||||
|
if err != nil {
|
||||||
|
// 原始模型名兼容透传:非统一模型 ID 不参与路由。
|
||||||
|
h.forwardPassthrough(c, inSpec, clientProtocol, ifaceType, isStream)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if providerID == "" || modelName == "" {
|
||||||
|
h.forwardPassthrough(c, inSpec, clientProtocol, ifaceType, isStream)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 路由
|
// 路由
|
||||||
routeResult, err := h.routingService.RouteByModelName(providerID, modelName)
|
routeResult, err := h.routingService.RouteByModelName(providerID, modelName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// GET 请求或无法提取 model 时,直接转发到上游
|
h.writeRouteError(c, err)
|
||||||
if len(body) == 0 || modelName == "" {
|
|
||||||
h.forwardPassthrough(c, inSpec, clientProtocol)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.writeError(c, err, clientProtocol)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,9 +155,6 @@ func (h *ProxyHandler) HandleProxy(c *gin.Context) {
|
|||||||
routeResult.Model.ModelName, // 上游模型名,用于请求改写
|
routeResult.Model.ModelName, // 上游模型名,用于请求改写
|
||||||
)
|
)
|
||||||
|
|
||||||
// 判断是否流式
|
|
||||||
isStream := h.isStreamRequest(body, clientProtocol, nativePath)
|
|
||||||
|
|
||||||
// 计算统一模型 ID(用于响应覆写)
|
// 计算统一模型 ID(用于响应覆写)
|
||||||
unifiedModelID := routeResult.Model.UnifiedModelID()
|
unifiedModelID := routeResult.Model.UnifiedModelID()
|
||||||
|
|
||||||
@@ -156,6 +165,28 @@ func (h *ProxyHandler) HandleProxy(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func supportsModelExtraction(ifaceType conversion.InterfaceType) bool {
|
||||||
|
switch ifaceType {
|
||||||
|
case conversion.InterfaceTypeChat, conversion.InterfaceTypeEmbeddings, conversion.InterfaceTypeRerank:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isInvalidJSONError(err error) bool {
|
||||||
|
var syntaxErr *json.SyntaxError
|
||||||
|
var typeErr *json.UnmarshalTypeError
|
||||||
|
return errors.As(err, &syntaxErr) || errors.As(err, &typeErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendRawQuery(path, rawQuery string) string {
|
||||||
|
if rawQuery == "" {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
return path + "?" + rawQuery
|
||||||
|
}
|
||||||
|
|
||||||
// handleNonStream 处理非流式请求
|
// handleNonStream 处理非流式请求
|
||||||
func (h *ProxyHandler) handleNonStream(c *gin.Context, inSpec conversion.HTTPRequestSpec, clientProtocol, providerProtocol string, targetProvider *conversion.TargetProvider, routeResult *domain.RouteResult, unifiedModelID string, ifaceType conversion.InterfaceType) {
|
func (h *ProxyHandler) handleNonStream(c *gin.Context, inSpec conversion.HTTPRequestSpec, clientProtocol, providerProtocol string, targetProvider *conversion.TargetProvider, routeResult *domain.RouteResult, unifiedModelID string, ifaceType conversion.InterfaceType) {
|
||||||
// 转换请求
|
// 转换请求
|
||||||
@@ -170,7 +201,11 @@ func (h *ProxyHandler) handleNonStream(c *gin.Context, inSpec conversion.HTTPReq
|
|||||||
resp, err := h.client.Send(c.Request.Context(), *outSpec)
|
resp, err := h.client.Send(c.Request.Context(), *outSpec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Error("发送请求失败", zap.Error(err))
|
h.logger.Error("发送请求失败", zap.Error(err))
|
||||||
h.writeConversionError(c, err, clientProtocol)
|
h.writeUpstreamUnavailable(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
h.writeUpstreamResponse(c, *resp)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,15 +217,7 @@ func (h *ProxyHandler) handleNonStream(c *gin.Context, inSpec conversion.HTTPReq
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置响应头
|
h.writeConvertedResponse(c, *convertedResp)
|
||||||
for k, v := range convertedResp.Headers {
|
|
||||||
c.Header(k, v)
|
|
||||||
}
|
|
||||||
if c.GetHeader("Content-Type") == "" {
|
|
||||||
c.Header("Content-Type", "application/json")
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Data(convertedResp.StatusCode, "application/json", convertedResp.Body)
|
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
_ = h.statsService.Record(routeResult.Provider.ID, routeResult.Model.ModelName) //nolint:errcheck // fire-and-forget 统计记录不阻塞请求
|
_ = h.statsService.Record(routeResult.Provider.ID, routeResult.Model.ModelName) //nolint:errcheck // fire-and-forget 统计记录不阻塞请求
|
||||||
@@ -206,15 +233,23 @@ func (h *ProxyHandler) handleStream(c *gin.Context, inSpec conversion.HTTPReques
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建流式转换器,传入 modelOverride(跨协议场景覆写 model 字段)
|
// 发送流式请求
|
||||||
streamConverter, err := h.engine.CreateStreamConverter(clientProtocol, providerProtocol, unifiedModelID, ifaceType)
|
streamResp, err := h.client.SendStream(c.Request.Context(), *outSpec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writeConversionError(c, err, clientProtocol)
|
h.writeUpstreamUnavailable(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if streamResp.StatusCode < http.StatusOK || streamResp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
h.writeUpstreamResponse(c, conversion.HTTPResponseSpec{
|
||||||
|
StatusCode: streamResp.StatusCode,
|
||||||
|
Headers: streamResp.Headers,
|
||||||
|
Body: streamResp.Body,
|
||||||
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发送流式请求
|
// 创建流式转换器,传入 modelOverride(跨协议场景覆写 model 字段)
|
||||||
eventChan, err := h.client.SendStream(c.Request.Context(), *outSpec)
|
streamConverter, err := h.engine.CreateStreamConverter(clientProtocol, providerProtocol, unifiedModelID, ifaceType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writeConversionError(c, err, clientProtocol)
|
h.writeConversionError(c, err, clientProtocol)
|
||||||
return
|
return
|
||||||
@@ -225,8 +260,9 @@ func (h *ProxyHandler) handleStream(c *gin.Context, inSpec conversion.HTTPReques
|
|||||||
c.Header("Connection", "keep-alive")
|
c.Header("Connection", "keep-alive")
|
||||||
|
|
||||||
writer := bufio.NewWriter(c.Writer)
|
writer := bufio.NewWriter(c.Writer)
|
||||||
|
flushed := false
|
||||||
|
|
||||||
for event := range eventChan {
|
for event := range streamResp.Events {
|
||||||
if event.Error != nil {
|
if event.Error != nil {
|
||||||
h.logger.Error("流读取错误", zap.Error(event.Error))
|
h.logger.Error("流读取错误", zap.Error(event.Error))
|
||||||
break
|
break
|
||||||
@@ -237,6 +273,7 @@ func (h *ProxyHandler) handleStream(c *gin.Context, inSpec conversion.HTTPReques
|
|||||||
if err := h.writeStreamChunks(writer, chunks); err != nil {
|
if err := h.writeStreamChunks(writer, chunks); err != nil {
|
||||||
h.logger.Warn("流式响应写回失败", zap.Error(err))
|
h.logger.Warn("流式响应写回失败", zap.Error(err))
|
||||||
}
|
}
|
||||||
|
flushed = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,6 +283,12 @@ func (h *ProxyHandler) handleStream(c *gin.Context, inSpec conversion.HTTPReques
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !flushed {
|
||||||
|
chunks := streamConverter.Flush()
|
||||||
|
if err := h.writeStreamChunks(writer, chunks); err != nil {
|
||||||
|
h.logger.Warn("流式响应写回失败", zap.Error(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
_ = h.statsService.Record(routeResult.Provider.ID, routeResult.Model.ModelName) //nolint:errcheck // fire-and-forget 统计记录不阻塞请求
|
_ = h.statsService.Record(routeResult.Provider.ID, routeResult.Model.ModelName) //nolint:errcheck // fire-and-forget 统计记录不阻塞请求
|
||||||
@@ -291,7 +334,7 @@ func (h *ProxyHandler) handleModelsList(c *gin.Context, adapter conversion.Proto
|
|||||||
models, err := h.providerService.ListEnabledModels()
|
models, err := h.providerService.ListEnabledModels()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Error("查询启用模型失败", zap.Error(err))
|
h.logger.Error("查询启用模型失败", zap.Error(err))
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "查询模型失败"})
|
h.writeProxyError(c, http.StatusInternalServerError, "CONVERSION_FAILED", "查询模型失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -313,7 +356,7 @@ func (h *ProxyHandler) handleModelsList(c *gin.Context, adapter conversion.Proto
|
|||||||
body, err := adapter.EncodeModelsResponse(modelList)
|
body, err := adapter.EncodeModelsResponse(modelList)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Error("编码 Models 响应失败", zap.Error(err))
|
h.logger.Error("编码 Models 响应失败", zap.Error(err))
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "编码响应失败"})
|
h.writeProxyError(c, http.StatusInternalServerError, "CONVERSION_FAILED", "编码响应失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,17 +368,14 @@ func (h *ProxyHandler) handleModelInfo(c *gin.Context, unifiedID string, adapter
|
|||||||
// 解析统一模型 ID
|
// 解析统一模型 ID
|
||||||
providerID, modelName, err := modelid.ParseUnifiedModelID(unifiedID)
|
providerID, modelName, err := modelid.ParseUnifiedModelID(unifiedID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{
|
h.writeProxyError(c, http.StatusBadRequest, "INVALID_MODEL_ID", "无效的统一模型 ID 格式")
|
||||||
"error": "无效的统一模型 ID 格式",
|
|
||||||
"code": "INVALID_MODEL_ID",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从数据库查询模型
|
// 从数据库查询模型
|
||||||
model, err := h.providerService.GetModelByProviderAndName(providerID, modelName)
|
model, err := h.providerService.GetModelByProviderAndName(providerID, modelName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "模型未找到"})
|
h.writeProxyError(c, http.StatusNotFound, "MODEL_NOT_FOUND", "模型未找到")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -351,46 +391,103 @@ func (h *ProxyHandler) handleModelInfo(c *gin.Context, unifiedID string, adapter
|
|||||||
body, err := adapter.EncodeModelInfoResponse(modelInfo)
|
body, err := adapter.EncodeModelInfoResponse(modelInfo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Error("编码 ModelInfo 响应失败", zap.Error(err))
|
h.logger.Error("编码 ModelInfo 响应失败", zap.Error(err))
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "编码响应失败"})
|
h.writeProxyError(c, http.StatusInternalServerError, "CONVERSION_FAILED", "编码响应失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Data(http.StatusOK, "application/json", body)
|
c.Data(http.StatusOK, "application/json", body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeConversionError 写入转换错误
|
// writeConversionError 写入网关层转换错误
|
||||||
func (h *ProxyHandler) writeConversionError(c *gin.Context, err error, clientProtocol string) {
|
func (h *ProxyHandler) writeConversionError(c *gin.Context, err error, clientProtocol string) {
|
||||||
var convErr *conversion.ConversionError
|
var convErr *conversion.ConversionError
|
||||||
if errors.As(err, &convErr) {
|
if errors.As(err, &convErr) {
|
||||||
body, statusCode, encodeErr := h.engine.EncodeError(convErr, clientProtocol)
|
statusCode, code, message := mapConversionError(convErr)
|
||||||
if encodeErr != nil {
|
h.writeProxyError(c, statusCode, code, message)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": encodeErr.Error()})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.Data(statusCode, "application/json", body)
|
h.writeProxyError(c, http.StatusInternalServerError, "CONVERSION_FAILED", err.Error())
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeError 写入路由错误
|
func mapConversionError(err *conversion.ConversionError) (int, string, string) {
|
||||||
func (h *ProxyHandler) writeError(c *gin.Context, err error, clientProtocol string) {
|
switch err.Code {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
case conversion.ErrorCodeJSONParseError:
|
||||||
|
if phase, ok := err.Details[conversion.ErrorDetailPhase].(string); ok && phase == conversion.ErrorPhaseRequest {
|
||||||
|
return http.StatusBadRequest, "INVALID_JSON", "请求体 JSON 格式错误"
|
||||||
|
}
|
||||||
|
return http.StatusInternalServerError, "CONVERSION_FAILED", err.Message
|
||||||
|
case conversion.ErrorCodeInvalidInput,
|
||||||
|
conversion.ErrorCodeMissingRequiredField,
|
||||||
|
conversion.ErrorCodeProtocolConstraint:
|
||||||
|
return http.StatusBadRequest, "INVALID_REQUEST", err.Message
|
||||||
|
case conversion.ErrorCodeInterfaceNotSupported:
|
||||||
|
return http.StatusBadRequest, "UNSUPPORTED_INTERFACE", err.Message
|
||||||
|
case conversion.ErrorCodeUnsupportedMultimodal:
|
||||||
|
return http.StatusBadRequest, "UNSUPPORTED_MULTIMODAL", err.Message
|
||||||
|
default:
|
||||||
|
return http.StatusInternalServerError, "CONVERSION_FAILED", err.Message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ProxyHandler) writeRouteError(c *gin.Context, err error) {
|
||||||
|
if appErr, ok := appErrors.AsAppError(err); ok {
|
||||||
|
switch appErr.Code {
|
||||||
|
case appErrors.ErrModelNotFound.Code, appErrors.ErrModelDisabled.Code:
|
||||||
|
h.writeProxyError(c, appErr.HTTPStatus, "MODEL_NOT_FOUND", appErr.Message)
|
||||||
|
case appErrors.ErrProviderNotFound.Code, appErrors.ErrProviderDisabled.Code:
|
||||||
|
h.writeProxyError(c, appErr.HTTPStatus, "PROVIDER_NOT_FOUND", appErr.Message)
|
||||||
|
default:
|
||||||
|
h.writeProxyError(c, appErr.HTTPStatus, "INVALID_REQUEST", appErr.Message)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.writeProxyError(c, http.StatusNotFound, "MODEL_NOT_FOUND", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ProxyHandler) writeUpstreamUnavailable(c *gin.Context, err error) {
|
||||||
|
h.logger.Error("上游不可达", zap.Error(err))
|
||||||
|
h.writeProxyError(c, http.StatusBadGateway, "UPSTREAM_UNAVAILABLE", "上游服务不可达")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ProxyHandler) writeProxyError(c *gin.Context, status int, code, message string) {
|
||||||
|
c.JSON(status, gin.H{
|
||||||
|
"error": message,
|
||||||
|
"code": code,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ProxyHandler) writeConvertedResponse(c *gin.Context, resp conversion.HTTPResponseSpec) {
|
||||||
|
for k, v := range resp.Headers {
|
||||||
|
c.Header(k, v)
|
||||||
|
}
|
||||||
|
contentType := headerValue(resp.Headers, "Content-Type")
|
||||||
|
if contentType == "" {
|
||||||
|
contentType = "application/json"
|
||||||
|
}
|
||||||
|
c.Data(resp.StatusCode, contentType, resp.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ProxyHandler) writeUpstreamResponse(c *gin.Context, resp conversion.HTTPResponseSpec) {
|
||||||
|
for k, v := range filterHopByHopHeaders(resp.Headers) {
|
||||||
|
c.Header(k, v)
|
||||||
|
}
|
||||||
|
contentType := headerValue(resp.Headers, "Content-Type")
|
||||||
|
c.Data(resp.StatusCode, contentType, resp.Body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// forwardPassthrough 直接转发请求到上游(用于 GET 等无 model 的请求)
|
// forwardPassthrough 直接转发请求到上游(用于 GET 等无 model 的请求)
|
||||||
func (h *ProxyHandler) forwardPassthrough(c *gin.Context, inSpec conversion.HTTPRequestSpec, clientProtocol string) {
|
func (h *ProxyHandler) forwardPassthrough(c *gin.Context, inSpec conversion.HTTPRequestSpec, clientProtocol string, ifaceType conversion.InterfaceType, isStream bool) {
|
||||||
registry := h.engine.GetRegistry()
|
registry := h.engine.GetRegistry()
|
||||||
adapter, err := registry.Get(clientProtocol)
|
adapter, err := registry.Get(clientProtocol)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的协议: " + clientProtocol})
|
h.writeProxyError(c, http.StatusNotFound, "UNSUPPORTED_INTERFACE", "不支持的协议: "+clientProtocol)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
providers, err := h.providerService.List()
|
providers, err := h.providerService.List()
|
||||||
if err != nil || len(providers) == 0 {
|
if err != nil || len(providers) == 0 {
|
||||||
h.logger.Warn("无可用供应商转发 GET 请求", zap.String("path", inSpec.URL))
|
h.logger.Warn("无可用供应商转发请求", zap.String("path", inSpec.URL))
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "没有可用的供应商。请先创建供应商和模型。"})
|
h.writeProxyError(c, http.StatusNotFound, "PROVIDER_NOT_FOUND", "没有可用的供应商。请先创建供应商和模型。")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,19 +497,18 @@ func (h *ProxyHandler) forwardPassthrough(c *gin.Context, inSpec conversion.HTTP
|
|||||||
providerProtocol = "openai"
|
providerProtocol = "openai"
|
||||||
}
|
}
|
||||||
|
|
||||||
ifaceType := adapter.DetectInterfaceType(inSpec.URL)
|
|
||||||
|
|
||||||
targetProvider := conversion.NewTargetProvider(p.BaseURL, p.APIKey, "")
|
targetProvider := conversion.NewTargetProvider(p.BaseURL, p.APIKey, "")
|
||||||
|
|
||||||
var outSpec *conversion.HTTPRequestSpec
|
var outSpec *conversion.HTTPRequestSpec
|
||||||
if clientProtocol == providerProtocol {
|
if clientProtocol == providerProtocol {
|
||||||
upstreamURL := p.BaseURL + inSpec.URL
|
upstreamPath := adapter.BuildUrl(stripRawQuery(inSpec.URL), ifaceType)
|
||||||
|
upstreamPath = appendRawQuery(upstreamPath, rawQueryFromPath(inSpec.URL))
|
||||||
headers := adapter.BuildHeaders(targetProvider)
|
headers := adapter.BuildHeaders(targetProvider)
|
||||||
if _, ok := headers["Content-Type"]; !ok {
|
if _, ok := headers["Content-Type"]; !ok {
|
||||||
headers["Content-Type"] = "application/json"
|
headers["Content-Type"] = "application/json"
|
||||||
}
|
}
|
||||||
outSpec = &conversion.HTTPRequestSpec{
|
outSpec = &conversion.HTTPRequestSpec{
|
||||||
URL: upstreamURL,
|
URL: joinBaseURL(p.BaseURL, upstreamPath),
|
||||||
Method: inSpec.Method,
|
Method: inSpec.Method,
|
||||||
Headers: headers,
|
Headers: headers,
|
||||||
Body: inSpec.Body,
|
Body: inSpec.Body,
|
||||||
@@ -425,9 +521,18 @@ func (h *ProxyHandler) forwardPassthrough(c *gin.Context, inSpec conversion.HTTP
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if isStream {
|
||||||
|
h.forwardStream(c, *outSpec, clientProtocol, providerProtocol, ifaceType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
resp, err := h.client.Send(c.Request.Context(), *outSpec)
|
resp, err := h.client.Send(c.Request.Context(), *outSpec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writeConversionError(c, err, clientProtocol)
|
h.writeUpstreamUnavailable(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
h.writeUpstreamResponse(c, *resp)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -437,13 +542,111 @@ func (h *ProxyHandler) forwardPassthrough(c *gin.Context, inSpec conversion.HTTP
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for k, v := range convertedResp.Headers {
|
h.writeConvertedResponse(c, *convertedResp)
|
||||||
c.Header(k, v)
|
|
||||||
}
|
}
|
||||||
if c.GetHeader("Content-Type") == "" {
|
|
||||||
c.Header("Content-Type", "application/json")
|
func (h *ProxyHandler) forwardStream(c *gin.Context, outSpec conversion.HTTPRequestSpec, clientProtocol, providerProtocol string, ifaceType conversion.InterfaceType) {
|
||||||
|
streamResp, err := h.client.SendStream(c.Request.Context(), outSpec)
|
||||||
|
if err != nil {
|
||||||
|
h.writeUpstreamUnavailable(c, err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
c.Data(convertedResp.StatusCode, "application/json", convertedResp.Body)
|
if streamResp.StatusCode < http.StatusOK || streamResp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
h.writeUpstreamResponse(c, conversion.HTTPResponseSpec{
|
||||||
|
StatusCode: streamResp.StatusCode,
|
||||||
|
Headers: streamResp.Headers,
|
||||||
|
Body: streamResp.Body,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
streamConverter, err := h.engine.CreateStreamConverter(clientProtocol, providerProtocol, "", ifaceType)
|
||||||
|
if err != nil {
|
||||||
|
h.writeConversionError(c, err, clientProtocol)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Header("Content-Type", "text/event-stream")
|
||||||
|
c.Header("Cache-Control", "no-cache")
|
||||||
|
c.Header("Connection", "keep-alive")
|
||||||
|
|
||||||
|
writer := bufio.NewWriter(c.Writer)
|
||||||
|
flushed := false
|
||||||
|
for event := range streamResp.Events {
|
||||||
|
if event.Error != nil {
|
||||||
|
h.logger.Error("透传流读取错误", zap.Error(event.Error))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if event.Done {
|
||||||
|
chunks := streamConverter.Flush()
|
||||||
|
if err := h.writeStreamChunks(writer, chunks); err != nil {
|
||||||
|
h.logger.Warn("透传流式响应写回失败", zap.Error(err))
|
||||||
|
}
|
||||||
|
flushed = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
chunks := streamConverter.ProcessChunk(event.Data)
|
||||||
|
if err := h.writeStreamChunks(writer, chunks); err != nil {
|
||||||
|
h.logger.Warn("透传流式响应写回失败", zap.Error(err))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !flushed {
|
||||||
|
chunks := streamConverter.Flush()
|
||||||
|
if err := h.writeStreamChunks(writer, chunks); err != nil {
|
||||||
|
h.logger.Warn("透传流式响应写回失败", zap.Error(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stripRawQuery(path string) string {
|
||||||
|
pathOnly, _, _ := strings.Cut(path, "?")
|
||||||
|
return pathOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
func rawQueryFromPath(path string) string {
|
||||||
|
_, rawQuery, found := strings.Cut(path, "?")
|
||||||
|
if !found {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return rawQuery
|
||||||
|
}
|
||||||
|
|
||||||
|
func joinBaseURL(baseURL, path string) string {
|
||||||
|
return strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(path, "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func headerValue(headers map[string]string, key string) string {
|
||||||
|
for k, v := range headers {
|
||||||
|
if strings.EqualFold(k, key) {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func filterHopByHopHeaders(headers map[string]string) map[string]string {
|
||||||
|
if len(headers) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
hopByHop := map[string]struct{}{
|
||||||
|
"connection": {},
|
||||||
|
"transfer-encoding": {},
|
||||||
|
"keep-alive": {},
|
||||||
|
"proxy-authenticate": {},
|
||||||
|
"proxy-authorization": {},
|
||||||
|
"te": {},
|
||||||
|
"trailer": {},
|
||||||
|
"upgrade": {},
|
||||||
|
}
|
||||||
|
filtered := make(map[string]string, len(headers))
|
||||||
|
for k, v := range headers {
|
||||||
|
if _, skip := hopByHop[strings.ToLower(k)]; skip {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
filtered[k] = v
|
||||||
|
}
|
||||||
|
return filtered
|
||||||
}
|
}
|
||||||
|
|
||||||
// extractHeaders 从 Gin context 提取请求头
|
// extractHeaders 从 Gin context 提取请求头
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -73,7 +74,7 @@ func TestProxyHandler_HandleProxy_NonStreamSuccess(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
@@ -92,8 +93,8 @@ func TestProxyHandler_HandleProxy_NonStreamSuccess(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -109,20 +110,20 @@ func TestProxyHandler_HandleProxy_RoutingError_WithBody(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(nil, appErrors.ErrModelNotFound)
|
routingSvc.EXPECT().RouteByModelName("unknown", "model").Return(nil, appErrors.ErrModelNotFound)
|
||||||
providerSvc := mocks.NewMockProviderService(ctrl)
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
providerSvc.EXPECT().List().Return(nil, nil)
|
|
||||||
client := mocks.NewMockProviderClient(ctrl)
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
statsSvc := mocks.NewMockStatsService(ctrl)
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"unknown","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"unknown/model","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 404, w.Code)
|
assert.Equal(t, 404, w.Code)
|
||||||
|
assert.Contains(t, w.Body.String(), "MODEL_NOT_FOUND")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_HandleProxy_ConversionError(t *testing.T) {
|
func TestProxyHandler_HandleProxy_ConversionError(t *testing.T) {
|
||||||
@@ -131,7 +132,7 @@ func TestProxyHandler_HandleProxy_ConversionError(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
@@ -145,11 +146,12 @@ func TestProxyHandler_HandleProxy_ConversionError(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 500, w.Code)
|
assert.Equal(t, 502, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"上游服务不可达","code":"UPSTREAM_UNAVAILABLE"}`, w.Body.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_HandleProxy_ClientSendError(t *testing.T) {
|
func TestProxyHandler_HandleProxy_ClientSendError(t *testing.T) {
|
||||||
@@ -158,7 +160,7 @@ func TestProxyHandler_HandleProxy_ClientSendError(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
@@ -172,11 +174,12 @@ func TestProxyHandler_HandleProxy_ClientSendError(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 500, w.Code)
|
assert.Equal(t, 502, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"上游服务不可达","code":"UPSTREAM_UNAVAILABLE"}`, w.Body.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_HandleProxy_StreamSuccess(t *testing.T) {
|
func TestProxyHandler_HandleProxy_StreamSuccess(t *testing.T) {
|
||||||
@@ -185,12 +188,12 @@ func TestProxyHandler_HandleProxy_StreamSuccess(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
client := mocks.NewMockProviderClient(ctrl)
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (<-chan provider.StreamEvent, error) {
|
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*provider.StreamResponse, error) {
|
||||||
ch := make(chan provider.StreamEvent, 10)
|
ch := make(chan provider.StreamEvent, 10)
|
||||||
go func() {
|
go func() {
|
||||||
defer close(ch)
|
defer close(ch)
|
||||||
@@ -199,7 +202,7 @@ func TestProxyHandler_HandleProxy_StreamSuccess(t *testing.T) {
|
|||||||
ch <- provider.StreamEvent{Data: []byte("data: [DONE]\n\n")}
|
ch <- provider.StreamEvent{Data: []byte("data: [DONE]\n\n")}
|
||||||
ch <- provider.StreamEvent{Done: true}
|
ch <- provider.StreamEvent{Done: true}
|
||||||
}()
|
}()
|
||||||
return ch, nil
|
return &provider.StreamResponse{StatusCode: 200, Headers: map[string]string{"Content-Type": "text/event-stream"}, Events: ch}, nil
|
||||||
})
|
})
|
||||||
providerSvc := mocks.NewMockProviderService(ctrl)
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
statsSvc := mocks.NewMockStatsService(ctrl)
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
@@ -208,13 +211,14 @@ func TestProxyHandler_HandleProxy_StreamSuccess(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
assert.Equal(t, "text/event-stream", w.Header().Get("Content-Type"))
|
assert.Equal(t, "text/event-stream", w.Header().Get("Content-Type"))
|
||||||
assert.Contains(t, w.Body.String(), "Hello")
|
assert.Contains(t, w.Body.String(), "Hello")
|
||||||
|
assert.Contains(t, w.Body.String(), "p1/gpt-4")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_HandleProxy_StreamError(t *testing.T) {
|
func TestProxyHandler_HandleProxy_StreamError(t *testing.T) {
|
||||||
@@ -223,12 +227,12 @@ func TestProxyHandler_HandleProxy_StreamError(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
client := mocks.NewMockProviderClient(ctrl)
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (<-chan provider.StreamEvent, error) {
|
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*provider.StreamResponse, error) {
|
||||||
return nil, context.DeadlineExceeded
|
return nil, context.DeadlineExceeded
|
||||||
})
|
})
|
||||||
providerSvc := mocks.NewMockProviderService(ctrl)
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
@@ -237,11 +241,12 @@ func TestProxyHandler_HandleProxy_StreamError(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 500, w.Code)
|
assert.Equal(t, 502, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"上游服务不可达","code":"UPSTREAM_UNAVAILABLE"}`, w.Body.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_ForwardPassthrough_GET(t *testing.T) {
|
func TestProxyHandler_ForwardPassthrough_GET(t *testing.T) {
|
||||||
@@ -261,8 +266,8 @@ func TestProxyHandler_ForwardPassthrough_GET(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -282,11 +287,11 @@ func TestProxyHandler_ForwardPassthrough_UnsupportedProtocol(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "unknown"}, {Key: "path", Value: "/models"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "unknown"}, {Key: "path", Value: "/v1/models"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/unknown/models", nil)
|
c.Request = httptest.NewRequest("GET", "/unknown/models", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 400, w.Code)
|
assert.Equal(t, 404, w.Code)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_ForwardPassthrough_NoProviders(t *testing.T) {
|
func TestProxyHandler_ForwardPassthrough_NoProviders(t *testing.T) {
|
||||||
@@ -304,8 +309,8 @@ func TestProxyHandler_ForwardPassthrough_NoProviders(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -329,7 +334,7 @@ func TestProxyHandler_HandleProxy_ProviderProtocolDefault(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
@@ -347,8 +352,8 @@ func TestProxyHandler_HandleProxy_ProviderProtocolDefault(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -371,6 +376,7 @@ func TestProxyHandler_WriteConversionError_NonConversionError(t *testing.T) {
|
|||||||
|
|
||||||
h.writeConversionError(c, context.DeadlineExceeded, "openai")
|
h.writeConversionError(c, context.DeadlineExceeded, "openai")
|
||||||
assert.Equal(t, 500, w.Code)
|
assert.Equal(t, 500, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"context deadline exceeded","code":"CONVERSION_FAILED"}`, w.Body.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_WriteConversionError_ConversionError(t *testing.T) {
|
func TestProxyHandler_WriteConversionError_ConversionError(t *testing.T) {
|
||||||
@@ -390,7 +396,40 @@ func TestProxyHandler_WriteConversionError_ConversionError(t *testing.T) {
|
|||||||
|
|
||||||
convErr := conversion.NewConversionError(conversion.ErrorCodeInvalidInput, "bad request")
|
convErr := conversion.NewConversionError(conversion.ErrorCodeInvalidInput, "bad request")
|
||||||
h.writeConversionError(c, convErr, "openai")
|
h.writeConversionError(c, convErr, "openai")
|
||||||
assert.Equal(t, 500, w.Code)
|
assert.Equal(t, 400, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"bad request","code":"INVALID_REQUEST"}`, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_WriteConversionError_JSONPhase(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
t.Run("request json parse error", func(t *testing.T) {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("POST", "/", nil)
|
||||||
|
|
||||||
|
h.writeConversionError(c, conversion.NewRequestJSONParseError("解码请求失败", context.Canceled), "openai")
|
||||||
|
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"请求体 JSON 格式错误","code":"INVALID_JSON"}`, w.Body.String())
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("response json parse error", func(t *testing.T) {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("POST", "/", nil)
|
||||||
|
|
||||||
|
h.writeConversionError(c, conversion.NewResponseJSONParseError("解码响应失败", context.Canceled), "openai")
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"解码响应失败","code":"CONVERSION_FAILED"}`, w.Body.String())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_HandleProxy_EmptyBody(t *testing.T) {
|
func TestProxyHandler_HandleProxy_EmptyBody(t *testing.T) {
|
||||||
@@ -410,8 +449,8 @@ func TestProxyHandler_HandleProxy_EmptyBody(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -423,19 +462,19 @@ func TestProxyHandler_HandleStream_MidStreamError(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
client := mocks.NewMockProviderClient(ctrl)
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (<-chan provider.StreamEvent, error) {
|
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*provider.StreamResponse, error) {
|
||||||
ch := make(chan provider.StreamEvent, 10)
|
ch := make(chan provider.StreamEvent, 10)
|
||||||
go func() {
|
go func() {
|
||||||
defer close(ch)
|
defer close(ch)
|
||||||
ch <- provider.StreamEvent{Data: []byte("data: {\"id\":\"1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"}}]}\n\n")}
|
ch <- provider.StreamEvent{Data: []byte("data: {\"id\":\"1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"}}]}\n\n")}
|
||||||
ch <- provider.StreamEvent{Error: fmt.Errorf("connection reset by peer")}
|
ch <- provider.StreamEvent{Error: fmt.Errorf("connection reset by peer")}
|
||||||
}()
|
}()
|
||||||
return ch, nil
|
return &provider.StreamResponse{StatusCode: 200, Headers: map[string]string{"Content-Type": "text/event-stream"}, Events: ch}, nil
|
||||||
})
|
})
|
||||||
providerSvc := mocks.NewMockProviderService(ctrl)
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
statsSvc := mocks.NewMockStatsService(ctrl)
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
@@ -444,8 +483,8 @@ func TestProxyHandler_HandleStream_MidStreamError(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -460,12 +499,12 @@ func TestProxyHandler_HandleStream_FlushOutput(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
client := mocks.NewMockProviderClient(ctrl)
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (<-chan provider.StreamEvent, error) {
|
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*provider.StreamResponse, error) {
|
||||||
ch := make(chan provider.StreamEvent, 10)
|
ch := make(chan provider.StreamEvent, 10)
|
||||||
go func() {
|
go func() {
|
||||||
defer close(ch)
|
defer close(ch)
|
||||||
@@ -473,7 +512,7 @@ func TestProxyHandler_HandleStream_FlushOutput(t *testing.T) {
|
|||||||
ch <- provider.StreamEvent{Data: []byte("data: [DONE]\n\n")}
|
ch <- provider.StreamEvent{Data: []byte("data: [DONE]\n\n")}
|
||||||
ch <- provider.StreamEvent{Done: true}
|
ch <- provider.StreamEvent{Done: true}
|
||||||
}()
|
}()
|
||||||
return ch, nil
|
return &provider.StreamResponse{StatusCode: 200, Headers: map[string]string{"Content-Type": "text/event-stream"}, Events: ch}, nil
|
||||||
})
|
})
|
||||||
providerSvc := mocks.NewMockProviderService(ctrl)
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
statsSvc := mocks.NewMockStatsService(ctrl)
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
@@ -482,8 +521,8 @@ func TestProxyHandler_HandleStream_FlushOutput(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -505,7 +544,7 @@ func TestProxyHandler_HandleStream_CreateStreamConverterError(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "nonexistent", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "nonexistent", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
@@ -516,8 +555,8 @@ func TestProxyHandler_HandleStream_CreateStreamConverterError(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 500, w.Code)
|
assert.Equal(t, 500, w.Code)
|
||||||
@@ -532,7 +571,7 @@ func TestProxyHandler_HandleStream_ConvertRequestError(t *testing.T) {
|
|||||||
require.NoError(t, registry.Register(openai.NewAdapter()))
|
require.NoError(t, registry.Register(openai.NewAdapter()))
|
||||||
|
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "nonexistent", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "nonexistent", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
@@ -543,8 +582,8 @@ func TestProxyHandler_HandleStream_ConvertRequestError(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 500, w.Code)
|
assert.Equal(t, 500, w.Code)
|
||||||
@@ -560,7 +599,7 @@ func TestProxyHandler_HandleNonStream_ConvertResponseError(t *testing.T) {
|
|||||||
require.NoError(t, registry.Register(anthropic.NewAdapter()))
|
require.NoError(t, registry.Register(anthropic.NewAdapter()))
|
||||||
|
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "anthropic", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "anthropic", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "claude-3", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "claude-3", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
@@ -578,8 +617,8 @@ func TestProxyHandler_HandleNonStream_ConvertResponseError(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"claude-3","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 500, w.Code)
|
assert.Equal(t, 500, w.Code)
|
||||||
@@ -591,7 +630,7 @@ func TestProxyHandler_HandleNonStream_ResponseHeaders(t *testing.T) {
|
|||||||
|
|
||||||
engine := setupProxyEngine(t)
|
engine := setupProxyEngine(t)
|
||||||
routingSvc := mocks.NewMockRoutingService(ctrl)
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
routingSvc.EXPECT().RouteByModelName("", "").Return(&domain.RouteResult{
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com", Protocol: "openai", Enabled: true},
|
||||||
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
@@ -610,8 +649,8 @@ func TestProxyHandler_HandleNonStream_ResponseHeaders(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -642,8 +681,8 @@ func TestProxyHandler_ForwardPassthrough_CrossProtocol(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -666,8 +705,8 @@ func TestProxyHandler_ForwardPassthrough_NoBody_NoModel(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -690,10 +729,10 @@ func TestIsStreamRequest_EdgeCases(t *testing.T) {
|
|||||||
path string
|
path string
|
||||||
expected bool
|
expected bool
|
||||||
}{
|
}{
|
||||||
{"stream at end of JSON", `{"messages":[],"stream":true}`, "/chat/completions", true},
|
{"stream at end of JSON", `{"messages":[],"stream":true}`, "/v1/chat/completions", true},
|
||||||
{"stream with spaces", `{"stream" : true}`, "/chat/completions", true},
|
{"stream with spaces", `{"stream" : true}`, "/v1/chat/completions", true},
|
||||||
{"stream embedded in string value", `{"model":"stream:true"}`, "/chat/completions", false},
|
{"stream embedded in string value", `{"model":"stream:true"}`, "/v1/chat/completions", false},
|
||||||
{"empty body", "", "/chat/completions", false},
|
{"empty body", "", "/v1/chat/completions", false},
|
||||||
{"stream true embeddings", `{"model":"text-emb","stream":true}`, "/v1/embeddings", false},
|
{"stream true embeddings", `{"model":"text-emb","stream":true}`, "/v1/embeddings", false},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -720,8 +759,9 @@ func TestProxyHandler_WriteError_RouteError(t *testing.T) {
|
|||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Request = httptest.NewRequest("POST", "/", nil)
|
c.Request = httptest.NewRequest("POST", "/", nil)
|
||||||
|
|
||||||
h.writeError(c, fmt.Errorf("model not found"), "openai")
|
h.writeRouteError(c, fmt.Errorf("model not found"))
|
||||||
assert.Equal(t, 404, w.Code)
|
assert.Equal(t, 404, w.Code)
|
||||||
|
assert.Contains(t, w.Body.String(), "MODEL_NOT_FOUND")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyHandler_HandleProxy_RouteEmptyBody_NoModel(t *testing.T) {
|
func TestProxyHandler_HandleProxy_RouteEmptyBody_NoModel(t *testing.T) {
|
||||||
@@ -741,8 +781,8 @@ func TestProxyHandler_HandleProxy_RouteEmptyBody_NoModel(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -765,35 +805,35 @@ func TestIsStreamRequest(t *testing.T) {
|
|||||||
name: "stream true",
|
name: "stream true",
|
||||||
body: []byte(`{"model": "gpt-4", "stream": true}`),
|
body: []byte(`{"model": "gpt-4", "stream": true}`),
|
||||||
clientProtocol: "openai",
|
clientProtocol: "openai",
|
||||||
nativePath: "/chat/completions",
|
nativePath: "/v1/chat/completions",
|
||||||
expected: true,
|
expected: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "stream false",
|
name: "stream false",
|
||||||
body: []byte(`{"model": "gpt-4", "stream": false}`),
|
body: []byte(`{"model": "gpt-4", "stream": false}`),
|
||||||
clientProtocol: "openai",
|
clientProtocol: "openai",
|
||||||
nativePath: "/chat/completions",
|
nativePath: "/v1/chat/completions",
|
||||||
expected: false,
|
expected: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "no stream field",
|
name: "no stream field",
|
||||||
body: []byte(`{"model": "gpt-4"}`),
|
body: []byte(`{"model": "gpt-4"}`),
|
||||||
clientProtocol: "openai",
|
clientProtocol: "openai",
|
||||||
nativePath: "/chat/completions",
|
nativePath: "/v1/chat/completions",
|
||||||
expected: false,
|
expected: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "invalid json",
|
name: "invalid json",
|
||||||
body: []byte(`{invalid}`),
|
body: []byte(`{invalid}`),
|
||||||
clientProtocol: "openai",
|
clientProtocol: "openai",
|
||||||
nativePath: "/chat/completions",
|
nativePath: "/v1/chat/completions",
|
||||||
expected: false,
|
expected: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "not chat endpoint",
|
name: "not chat endpoint",
|
||||||
body: []byte(`{"model": "gpt-4", "stream": true}`),
|
body: []byte(`{"model": "gpt-4", "stream": true}`),
|
||||||
clientProtocol: "openai",
|
clientProtocol: "openai",
|
||||||
nativePath: "/models",
|
nativePath: "/v1/models",
|
||||||
expected: false,
|
expected: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -831,8 +871,8 @@ func TestProxyHandler_HandleProxy_Models_LocalAggregation(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -862,8 +902,8 @@ func TestProxyHandler_HandleProxy_ModelInfo_LocalQuery(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models/openai/gpt-4"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models/openai/gpt-4"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models/openai/gpt-4", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models/openai/gpt-4", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -896,8 +936,8 @@ func TestProxyHandler_HandleProxy_Models_EmptySuffix_ForwardPassthrough(t *testi
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/models/"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/models/"}}
|
||||||
c.Request = httptest.NewRequest("GET", "/openai/models/", nil)
|
c.Request = httptest.NewRequest("GET", "/openai/v1/models/", nil)
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -934,8 +974,8 @@ func TestProxyHandler_HandleProxy_SmartPassthrough_UnifiedID(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"openai_p/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"openai_p/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -972,8 +1012,8 @@ func TestProxyHandler_HandleProxy_CrossProtocol_NonStream_UnifiedID(t *testing.T
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"anthropic_p/claude-3","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"anthropic_p/claude-3","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -994,7 +1034,7 @@ func TestProxyHandler_HandleProxy_CrossProtocol_Stream_UnifiedID(t *testing.T) {
|
|||||||
Model: &domain.Model{ID: "m1", ProviderID: "anthropic_p", ModelName: "claude-3", Enabled: true},
|
Model: &domain.Model{ID: "m1", ProviderID: "anthropic_p", ModelName: "claude-3", Enabled: true},
|
||||||
}, nil)
|
}, nil)
|
||||||
client := mocks.NewMockProviderClient(ctrl)
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (<-chan provider.StreamEvent, error) {
|
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*provider.StreamResponse, error) {
|
||||||
ch := make(chan provider.StreamEvent, 10)
|
ch := make(chan provider.StreamEvent, 10)
|
||||||
go func() {
|
go func() {
|
||||||
defer close(ch)
|
defer close(ch)
|
||||||
@@ -1012,7 +1052,7 @@ data: {"type":"message_stop"}
|
|||||||
`)}
|
`)}
|
||||||
ch <- provider.StreamEvent{Done: true}
|
ch <- provider.StreamEvent{Done: true}
|
||||||
}()
|
}()
|
||||||
return ch, nil
|
return &provider.StreamResponse{StatusCode: 200, Headers: map[string]string{"Content-Type": "text/event-stream"}, Events: ch}, nil
|
||||||
})
|
})
|
||||||
providerSvc := mocks.NewMockProviderService(ctrl)
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
statsSvc := mocks.NewMockStatsService(ctrl)
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
@@ -1021,8 +1061,8 @@ data: {"type":"message_stop"}
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"anthropic_p/claude-3","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"anthropic_p/claude-3","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -1059,8 +1099,8 @@ func TestProxyHandler_HandleProxy_SmartPassthrough_Fidelity(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"openai_p/gpt-4","messages":[{"role":"user","content":"hi"}],"custom_param":"should_be_preserved"}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"openai_p/gpt-4","messages":[{"role":"user","content":"hi"}],"custom_param":"should_be_preserved"}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 200, w.Code)
|
assert.Equal(t, 200, w.Code)
|
||||||
@@ -1090,8 +1130,8 @@ func TestProxyHandler_HandleProxy_UnifiedID_ModelNotFound(t *testing.T) {
|
|||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
c, _ := gin.CreateTestContext(w)
|
c, _ := gin.CreateTestContext(w)
|
||||||
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/chat/completions"}}
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
c.Request = httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader([]byte(`{"model":"unknown/model","messages":[{"role":"user","content":"hi"}]}`)))
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"unknown/model","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
h.HandleProxy(c)
|
h.HandleProxy(c)
|
||||||
assert.Equal(t, 404, w.Code)
|
assert.Equal(t, 404, w.Code)
|
||||||
@@ -1100,3 +1140,314 @@ func TestProxyHandler_HandleProxy_UnifiedID_ModelNotFound(t *testing.T) {
|
|||||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||||
assert.Contains(t, resp, "error")
|
assert.Contains(t, resp, "error")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_HandleProxy_OpenAIAndAnthropicNativePaths(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
protocol string
|
||||||
|
path string
|
||||||
|
requestPath string
|
||||||
|
baseURL string
|
||||||
|
expectedURL string
|
||||||
|
body string
|
||||||
|
responseBody string
|
||||||
|
responseModel string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "openai path keeps v1 after gateway prefix",
|
||||||
|
protocol: "openai",
|
||||||
|
path: "/v1/chat/completions",
|
||||||
|
requestPath: "/openai/v1/chat/completions",
|
||||||
|
baseURL: "https://api.test.com/v1",
|
||||||
|
expectedURL: "https://api.test.com/v1/chat/completions",
|
||||||
|
body: `{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}]}`,
|
||||||
|
responseBody: `{"id":"r1","object":"chat.completion","model":"gpt-4","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`,
|
||||||
|
responseModel: "p1/gpt-4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "anthropic path keeps v1 after gateway prefix",
|
||||||
|
protocol: "anthropic",
|
||||||
|
path: "/v1/messages",
|
||||||
|
requestPath: "/anthropic/v1/messages",
|
||||||
|
baseURL: "https://api.anthropic.test",
|
||||||
|
expectedURL: "https://api.anthropic.test/v1/messages",
|
||||||
|
body: `{"model":"p1/gpt-4","max_tokens":1024,"messages":[{"role":"user","content":"hi"}]}`,
|
||||||
|
responseBody: `{"id":"msg-1","type":"message","role":"assistant","model":"gpt-4","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`,
|
||||||
|
responseModel: "p1/gpt-4",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: tt.baseURL, Protocol: tt.protocol, Enabled: true},
|
||||||
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
|
}, nil)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
client.EXPECT().Send(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*conversion.HTTPResponseSpec, error) {
|
||||||
|
assert.Equal(t, tt.expectedURL, spec.URL)
|
||||||
|
return &conversion.HTTPResponseSpec{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Headers: map[string]string{"Content-Type": "application/json"},
|
||||||
|
Body: []byte(tt.responseBody),
|
||||||
|
}, nil
|
||||||
|
})
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
statsSvc.EXPECT().Record(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Params = gin.Params{{Key: "protocol", Value: tt.protocol}, {Key: "path", Value: tt.path}}
|
||||||
|
c.Request = httptest.NewRequest("POST", tt.requestPath, bytes.NewReader([]byte(tt.body)))
|
||||||
|
|
||||||
|
h.HandleProxy(c)
|
||||||
|
require.Equal(t, http.StatusOK, w.Code)
|
||||||
|
assert.Contains(t, w.Body.String(), tt.responseModel)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_UpstreamNon2xx_Passthrough(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com/v1", Protocol: "openai", Enabled: true},
|
||||||
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
|
}, nil)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
client.EXPECT().Send(gomock.Any(), gomock.Any()).Return(&conversion.HTTPResponseSpec{
|
||||||
|
StatusCode: http.StatusTooManyRequests,
|
||||||
|
Headers: map[string]string{
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Upstream-Error": "rate-limit",
|
||||||
|
"Transfer-Encoding": "chunked",
|
||||||
|
},
|
||||||
|
Body: []byte(`{"error":{"message":"rate limited"}}`),
|
||||||
|
}, nil)
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}]}`)))
|
||||||
|
|
||||||
|
h.HandleProxy(c)
|
||||||
|
require.Equal(t, http.StatusTooManyRequests, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":{"message":"rate limited"}}`, w.Body.String())
|
||||||
|
assert.Equal(t, "rate-limit", w.Header().Get("X-Upstream-Error"))
|
||||||
|
assert.Empty(t, w.Header().Get("Transfer-Encoding"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_StreamUpstreamNon2xx_Passthrough(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com/v1", Protocol: "openai", Enabled: true},
|
||||||
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
|
}, nil)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).Return(&provider.StreamResponse{
|
||||||
|
StatusCode: http.StatusServiceUnavailable,
|
||||||
|
Headers: map[string]string{"Content-Type": "application/json", "Connection": "close"},
|
||||||
|
Body: []byte(`{"error":"upstream down"}`),
|
||||||
|
}, nil)
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
|
h.HandleProxy(c)
|
||||||
|
require.Equal(t, http.StatusServiceUnavailable, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"upstream down"}`, w.Body.String())
|
||||||
|
assert.Empty(t, w.Header().Get("Connection"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterHopByHopHeaders(t *testing.T) {
|
||||||
|
filtered := filterHopByHopHeaders(map[string]string{
|
||||||
|
"Connection": "close",
|
||||||
|
"Transfer-Encoding": "chunked",
|
||||||
|
"Keep-Alive": "timeout=5",
|
||||||
|
"Proxy-Authenticate": "Basic",
|
||||||
|
"Proxy-Authorization": "Basic token",
|
||||||
|
"TE": "trailers",
|
||||||
|
"Trailer": "Expires",
|
||||||
|
"Upgrade": "websocket",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Request-ID": "req-1",
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(t, map[string]string{
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Request-ID": "req-1",
|
||||||
|
}, filtered)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_UnknownInterface_DoesNotGuessModel(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
providerSvc.EXPECT().List().Return([]domain.Provider{
|
||||||
|
{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com/v1", Protocol: "openai", Enabled: true},
|
||||||
|
}, nil)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
client.EXPECT().Send(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*conversion.HTTPResponseSpec, error) {
|
||||||
|
assert.Equal(t, "https://api.test.com/v1/unknown?trace=1", spec.URL)
|
||||||
|
assert.JSONEq(t, `{"model":"p1/gpt-4","payload":true}`, string(spec.Body))
|
||||||
|
return &conversion.HTTPResponseSpec{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Headers: map[string]string{"Content-Type": "application/json"},
|
||||||
|
Body: []byte(`{"ok":true}`),
|
||||||
|
}, nil
|
||||||
|
})
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/unknown"}}
|
||||||
|
c.Request = httptest.NewRequest("POST", "/openai/unknown?trace=1", bytes.NewReader([]byte(`{"model":"p1/gpt-4","payload":true}`)))
|
||||||
|
|
||||||
|
h.HandleProxy(c)
|
||||||
|
require.Equal(t, http.StatusOK, w.Code)
|
||||||
|
assert.JSONEq(t, `{"ok":true}`, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_InvalidJSON_UsesGatewayError(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":`)))
|
||||||
|
|
||||||
|
h.HandleProxy(c)
|
||||||
|
require.Equal(t, http.StatusBadRequest, w.Code)
|
||||||
|
assert.JSONEq(t, `{"error":"请求体 JSON 格式错误","code":"INVALID_JSON"}`, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_CrossProtocolMultimodal_Unsupported(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
routingSvc.EXPECT().RouteByModelName("anthropic_p", "claude").Return(&domain.RouteResult{
|
||||||
|
Provider: &domain.Provider{ID: "anthropic_p", Name: "Anthropic", APIKey: "sk-test", BaseURL: "https://api.anthropic.test", Protocol: "anthropic", Enabled: true},
|
||||||
|
Model: &domain.Model{ID: "m1", ProviderID: "anthropic_p", ModelName: "claude", Enabled: true},
|
||||||
|
}, nil)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
body := []byte(`{"model":"anthropic_p/claude","messages":[{"role":"user","content":[{"type":"text","text":"describe"},{"type":"image_url","image_url":{"url":"data:image/png;base64,abc"}}]}]}`)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
|
|
||||||
|
h.HandleProxy(c)
|
||||||
|
require.Equal(t, http.StatusBadRequest, w.Code)
|
||||||
|
assert.Contains(t, w.Body.String(), "UNSUPPORTED_MULTIMODAL")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_SameProtocolMultimodal_SmartPassthrough(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
routingSvc.EXPECT().RouteByModelName("p1", "gpt-4").Return(&domain.RouteResult{
|
||||||
|
Provider: &domain.Provider{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com/v1", Protocol: "openai", Enabled: true},
|
||||||
|
Model: &domain.Model{ID: "m1", ProviderID: "p1", ModelName: "gpt-4", Enabled: true},
|
||||||
|
}, nil)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
client.EXPECT().Send(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*conversion.HTTPResponseSpec, error) {
|
||||||
|
assert.Contains(t, string(spec.Body), "image_url")
|
||||||
|
assert.Contains(t, string(spec.Body), `"model":"gpt-4"`)
|
||||||
|
return &conversion.HTTPResponseSpec{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Headers: map[string]string{"Content-Type": "application/json"},
|
||||||
|
Body: []byte(`{"id":"r1","object":"chat.completion","model":"gpt-4","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`),
|
||||||
|
}, nil
|
||||||
|
})
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
statsSvc.EXPECT().Record(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
body := []byte(`{"model":"p1/gpt-4","messages":[{"role":"user","content":[{"type":"text","text":"describe"},{"type":"image_url","image_url":{"url":"data:image/png;base64,abc"}}]}]}`)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
|
|
||||||
|
h.HandleProxy(c)
|
||||||
|
require.Equal(t, http.StatusOK, w.Code)
|
||||||
|
assert.Contains(t, w.Body.String(), "p1/gpt-4")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyHandler_RawStreamPassthrough_PreservesSSEFrames(t *testing.T) {
|
||||||
|
ctrl := gomock.NewController(t)
|
||||||
|
defer ctrl.Finish()
|
||||||
|
|
||||||
|
engine := setupProxyEngine(t)
|
||||||
|
routingSvc := mocks.NewMockRoutingService(ctrl)
|
||||||
|
providerSvc := mocks.NewMockProviderService(ctrl)
|
||||||
|
providerSvc.EXPECT().List().Return([]domain.Provider{
|
||||||
|
{ID: "p1", Name: "Test", APIKey: "sk-test", BaseURL: "https://api.test.com/v1", Protocol: "openai", Enabled: true},
|
||||||
|
}, nil)
|
||||||
|
client := mocks.NewMockProviderClient(ctrl)
|
||||||
|
client.EXPECT().SendStream(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec conversion.HTTPRequestSpec) (*provider.StreamResponse, error) {
|
||||||
|
assert.Contains(t, string(spec.Body), `"model":"gpt-4"`)
|
||||||
|
ch := make(chan provider.StreamEvent, 3)
|
||||||
|
go func() {
|
||||||
|
defer close(ch)
|
||||||
|
ch <- provider.StreamEvent{Data: []byte("data: {\"model\":\"gpt-4\",\"choices\":[]}\n\n")}
|
||||||
|
ch <- provider.StreamEvent{Data: []byte("data: [DONE]\n\n")}
|
||||||
|
ch <- provider.StreamEvent{Done: true}
|
||||||
|
}()
|
||||||
|
return &provider.StreamResponse{StatusCode: http.StatusOK, Headers: map[string]string{"Content-Type": "text/event-stream"}, Events: ch}, nil
|
||||||
|
})
|
||||||
|
statsSvc := mocks.NewMockStatsService(ctrl)
|
||||||
|
h := newTestProxyHandler(engine, client, routingSvc, providerSvc, statsSvc)
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Params = gin.Params{{Key: "protocol", Value: "openai"}, {Key: "path", Value: "/v1/chat/completions"}}
|
||||||
|
c.Request = httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader([]byte(`{"model":"gpt-4","messages":[{"role":"user","content":"hi"}],"stream":true}`)))
|
||||||
|
|
||||||
|
h.HandleProxy(c)
|
||||||
|
require.Equal(t, http.StatusOK, w.Code)
|
||||||
|
assert.Equal(t, "data: {\"model\":\"gpt-4\",\"choices\":[]}\n\ndata: [DONE]\n\n", w.Body.String())
|
||||||
|
}
|
||||||
|
|||||||
26
backend/internal/handler/version_handler.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"nex/backend/pkg/buildinfo"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// VersionHandler 提供后端构建版本信息。
|
||||||
|
type VersionHandler struct{}
|
||||||
|
|
||||||
|
// NewVersionHandler 创建版本信息处理器。
|
||||||
|
func NewVersionHandler() *VersionHandler {
|
||||||
|
return &VersionHandler{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVersion 返回构建注入的版本元数据。
|
||||||
|
func (h *VersionHandler) GetVersion(c *gin.Context) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"version": buildinfo.Version(),
|
||||||
|
"commit": buildinfo.Commit(),
|
||||||
|
"build_time": buildinfo.BuildTime(),
|
||||||
|
})
|
||||||
|
}
|
||||||
31
backend/internal/handler/version_handler_test.go
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestVersionHandler_GetVersion(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
h := NewVersionHandler()
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/api/version", nil)
|
||||||
|
|
||||||
|
h.GetVersion(c)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, w.Code)
|
||||||
|
|
||||||
|
var result map[string]string
|
||||||
|
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
|
||||||
|
assert.Equal(t, "dev", result["version"])
|
||||||
|
assert.Equal(t, "unknown", result["commit"])
|
||||||
|
assert.Equal(t, "unknown", result["build_time"])
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -43,6 +44,14 @@ type StreamEvent struct {
|
|||||||
Done bool
|
Done bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StreamResponse 表示上游流式 HTTP 响应。
|
||||||
|
type StreamResponse struct {
|
||||||
|
StatusCode int
|
||||||
|
Headers map[string]string
|
||||||
|
Body []byte
|
||||||
|
Events <-chan StreamEvent
|
||||||
|
}
|
||||||
|
|
||||||
// Client 协议无关的供应商客户端
|
// Client 协议无关的供应商客户端
|
||||||
type Client struct {
|
type Client struct {
|
||||||
httpClient *http.Client
|
httpClient *http.Client
|
||||||
@@ -55,7 +64,7 @@ type Client struct {
|
|||||||
//go:generate go run go.uber.org/mock/mockgen -source=client.go -destination=../../tests/mocks/mock_provider_client.go -package=mocks
|
//go:generate go run go.uber.org/mock/mockgen -source=client.go -destination=../../tests/mocks/mock_provider_client.go -package=mocks
|
||||||
type ProviderClient interface {
|
type ProviderClient interface {
|
||||||
Send(ctx context.Context, spec conversion.HTTPRequestSpec) (*conversion.HTTPResponseSpec, error)
|
Send(ctx context.Context, spec conversion.HTTPRequestSpec) (*conversion.HTTPResponseSpec, error)
|
||||||
SendStream(ctx context.Context, spec conversion.HTTPRequestSpec) (<-chan StreamEvent, error)
|
SendStream(ctx context.Context, spec conversion.HTTPRequestSpec) (*StreamResponse, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient 创建供应商客户端
|
// NewClient 创建供应商客户端
|
||||||
@@ -116,7 +125,7 @@ func (c *Client) Send(ctx context.Context, spec conversion.HTTPRequestSpec) (*co
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SendStream 发送流式请求
|
// SendStream 发送流式请求
|
||||||
func (c *Client) SendStream(ctx context.Context, spec conversion.HTTPRequestSpec) (<-chan StreamEvent, error) {
|
func (c *Client) SendStream(ctx context.Context, spec conversion.HTTPRequestSpec) (*StreamResponse, error) {
|
||||||
var bodyReader io.Reader
|
var bodyReader io.Reader
|
||||||
if len(spec.Body) > 0 {
|
if len(spec.Body) > 0 {
|
||||||
bodyReader = bytes.NewReader(spec.Body)
|
bodyReader = bytes.NewReader(spec.Body)
|
||||||
@@ -139,23 +148,29 @@ func (c *Client) SendStream(ctx context.Context, spec conversion.HTTPRequestSpec
|
|||||||
return nil, pkgErrors.ErrRequestSend.WithCause(err)
|
return nil, pkgErrors.ErrRequestSend.WithCause(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
respHeaders := extractResponseHeaders(resp.Header)
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
cancel()
|
cancel()
|
||||||
errBody, readErr := io.ReadAll(resp.Body)
|
errBody, readErr := io.ReadAll(resp.Body)
|
||||||
if readErr != nil {
|
if readErr != nil {
|
||||||
return nil, fmt.Errorf("供应商返回错误: HTTP %d,读取错误响应失败: %w", resp.StatusCode, readErr)
|
return nil, pkgErrors.ErrResponseRead.WithCause(readErr)
|
||||||
}
|
}
|
||||||
if len(errBody) > 0 {
|
return &StreamResponse{
|
||||||
return nil, fmt.Errorf("供应商返回错误: HTTP %d: %s", resp.StatusCode, string(errBody))
|
StatusCode: resp.StatusCode,
|
||||||
}
|
Headers: respHeaders,
|
||||||
return nil, fmt.Errorf("供应商返回错误: HTTP %d", resp.StatusCode)
|
Body: errBody,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
eventChan := make(chan StreamEvent, c.streamCfg.ChannelBufferSize)
|
eventChan := make(chan StreamEvent, c.streamCfg.ChannelBufferSize)
|
||||||
go c.readStream(streamCtx, cancel, resp.Body, eventChan)
|
go c.readStream(streamCtx, cancel, resp.Body, eventChan)
|
||||||
|
|
||||||
return eventChan, nil
|
return &StreamResponse{
|
||||||
|
StatusCode: resp.StatusCode,
|
||||||
|
Headers: respHeaders,
|
||||||
|
Events: eventChan,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// readStream 读取 SSE 流
|
// readStream 读取 SSE 流
|
||||||
@@ -208,15 +223,17 @@ func (c *Client) readStream(ctx context.Context, cancel context.CancelFunc, body
|
|||||||
}
|
}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
idx := bytes.Index(dataBuf, []byte("\n\n"))
|
idx, sepLen := findSSEFrameSeparator(dataBuf)
|
||||||
if idx == -1 {
|
if idx == -1 {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
rawEvent := dataBuf[:idx]
|
frameEnd := idx + sepLen
|
||||||
dataBuf = dataBuf[idx+2:]
|
rawEvent := append([]byte(nil), dataBuf[:frameEnd]...)
|
||||||
|
dataBuf = dataBuf[frameEnd:]
|
||||||
|
|
||||||
if bytes.Contains(rawEvent, []byte("data: [DONE]")) {
|
if isSSEDoneFrame(rawEvent) {
|
||||||
|
eventChan <- StreamEvent{Data: rawEvent}
|
||||||
eventChan <- StreamEvent{Done: true}
|
eventChan <- StreamEvent{Done: true}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -225,11 +242,66 @@ func (c *Client) readStream(ctx context.Context, cancel context.CancelFunc, body
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err == io.EOF {
|
if err == io.EOF {
|
||||||
|
if len(dataBuf) > 0 {
|
||||||
|
eventChan <- StreamEvent{Data: dataBuf}
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isSSEDoneFrame(frame []byte) bool {
|
||||||
|
payload, ok := sseFrameDataPayload(frame)
|
||||||
|
return ok && strings.TrimSpace(payload) == "[DONE]"
|
||||||
|
}
|
||||||
|
|
||||||
|
func sseFrameDataPayload(frame []byte) (string, bool) {
|
||||||
|
text := strings.TrimRight(string(frame), "\r\n")
|
||||||
|
lines := strings.Split(text, "\n")
|
||||||
|
var dataLines []string
|
||||||
|
for _, line := range lines {
|
||||||
|
line = strings.TrimRight(line, "\r")
|
||||||
|
if strings.HasPrefix(line, "data:") {
|
||||||
|
value := strings.TrimPrefix(line, "data:")
|
||||||
|
if strings.HasPrefix(value, " ") {
|
||||||
|
value = value[1:]
|
||||||
|
}
|
||||||
|
dataLines = append(dataLines, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(dataLines) == 0 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return strings.Join(dataLines, "\n"), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractResponseHeaders(header http.Header) map[string]string {
|
||||||
|
respHeaders := make(map[string]string)
|
||||||
|
for k, vs := range header {
|
||||||
|
if len(vs) > 0 {
|
||||||
|
respHeaders[k] = vs[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return respHeaders
|
||||||
|
}
|
||||||
|
|
||||||
|
func findSSEFrameSeparator(data []byte) (int, int) {
|
||||||
|
lf := bytes.Index(data, []byte("\n\n"))
|
||||||
|
crlf := bytes.Index(data, []byte("\r\n\r\n"))
|
||||||
|
switch {
|
||||||
|
case lf < 0 && crlf < 0:
|
||||||
|
return -1, 0
|
||||||
|
case lf < 0:
|
||||||
|
return crlf, 4
|
||||||
|
case crlf < 0:
|
||||||
|
return lf, 2
|
||||||
|
case crlf <= lf:
|
||||||
|
return crlf, 4
|
||||||
|
default:
|
||||||
|
return lf, 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// isNetworkError 判断是否为网络相关错误
|
// isNetworkError 判断是否为网络相关错误
|
||||||
func isNetworkError(err error) bool {
|
func isNetworkError(err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
|||||||
@@ -110,11 +110,13 @@ func TestClient_SendStream_CreatesChannel(t *testing.T) {
|
|||||||
Body: []byte(`{}`),
|
Body: []byte(`{}`),
|
||||||
}
|
}
|
||||||
|
|
||||||
eventChan, err := client.SendStream(context.Background(), spec)
|
streamResp, err := client.SendStream(context.Background(), spec)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NotNil(t, eventChan)
|
require.NotNil(t, streamResp)
|
||||||
|
require.Equal(t, http.StatusOK, streamResp.StatusCode)
|
||||||
|
require.NotNil(t, streamResp.Events)
|
||||||
|
|
||||||
for range eventChan {
|
for range streamResp.Events {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,8 +134,10 @@ func TestClient_SendStream_ErrorResponse(t *testing.T) {
|
|||||||
Body: []byte(`{}`),
|
Body: []byte(`{}`),
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := client.SendStream(context.Background(), spec)
|
streamResp, err := client.SendStream(context.Background(), spec)
|
||||||
assert.Error(t, err)
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, streamResp)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, streamResp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClient_SendStream_SSEEvents(t *testing.T) {
|
func TestClient_SendStream_SSEEvents(t *testing.T) {
|
||||||
@@ -164,12 +168,13 @@ func TestClient_SendStream_SSEEvents(t *testing.T) {
|
|||||||
Body: []byte(`{"model":"gpt-4","messages":[],"stream":true}`),
|
Body: []byte(`{"model":"gpt-4","messages":[],"stream":true}`),
|
||||||
}
|
}
|
||||||
|
|
||||||
eventChan, err := client.SendStream(context.Background(), spec)
|
streamResp, err := client.SendStream(context.Background(), spec)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, streamResp)
|
||||||
|
|
||||||
var dataEvents [][]byte
|
var dataEvents [][]byte
|
||||||
var doneEvents int
|
var doneEvents int
|
||||||
for event := range eventChan {
|
for event := range streamResp.Events {
|
||||||
switch {
|
switch {
|
||||||
case event.Done:
|
case event.Done:
|
||||||
doneEvents++
|
doneEvents++
|
||||||
@@ -180,9 +185,56 @@ func TestClient_SendStream_SSEEvents(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
assert.Equal(t, 2, len(dataEvents), "expected exactly 2 data events from SSE stream")
|
assert.Equal(t, 3, len(dataEvents), "expected 2 data frames plus DONE frame from SSE stream")
|
||||||
assert.Contains(t, string(dataEvents[0]), "Hello")
|
assert.Contains(t, string(dataEvents[0]), "Hello")
|
||||||
assert.Contains(t, string(dataEvents[1]), "World")
|
assert.Contains(t, string(dataEvents[1]), "World")
|
||||||
|
assert.Contains(t, string(dataEvents[2]), "[DONE]")
|
||||||
|
assert.Equal(t, 1, doneEvents)
|
||||||
|
assert.Contains(t, string(dataEvents[0]), "\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClient_SendStream_DONEOnlyWhenDataPayloadEqualsDone(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
flusher, ok := w.(http.Flusher)
|
||||||
|
require.True(t, ok)
|
||||||
|
_, err := w.Write([]byte("data: {\"text\":\"data: [DONE] is plain text\"}\n\n"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
flusher.Flush()
|
||||||
|
_, err = w.Write([]byte("data: [DONE]\n\n"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
flusher.Flush()
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
client := NewClient(zap.NewNop())
|
||||||
|
spec := conversion.HTTPRequestSpec{
|
||||||
|
URL: server.URL + "/v1/chat/completions",
|
||||||
|
Method: "POST",
|
||||||
|
Body: []byte(`{}`),
|
||||||
|
}
|
||||||
|
|
||||||
|
streamResp, err := client.SendStream(context.Background(), spec)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, streamResp)
|
||||||
|
|
||||||
|
var dataEvents [][]byte
|
||||||
|
var doneEvents int
|
||||||
|
for event := range streamResp.Events {
|
||||||
|
switch {
|
||||||
|
case event.Done:
|
||||||
|
doneEvents++
|
||||||
|
case event.Error != nil:
|
||||||
|
t.Fatalf("unexpected error: %v", event.Error)
|
||||||
|
default:
|
||||||
|
dataEvents = append(dataEvents, event.Data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
require.Len(t, dataEvents, 2)
|
||||||
|
assert.Contains(t, string(dataEvents[0]), "plain text")
|
||||||
|
assert.Contains(t, string(dataEvents[1]), "[DONE]")
|
||||||
assert.Equal(t, 1, doneEvents)
|
assert.Equal(t, 1, doneEvents)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,13 +255,13 @@ func TestClient_SendStream_ContextCancellation(t *testing.T) {
|
|||||||
Body: []byte(`{}`),
|
Body: []byte(`{}`),
|
||||||
}
|
}
|
||||||
|
|
||||||
eventChan, err := client.SendStream(ctx, spec)
|
streamResp, err := client.SendStream(ctx, spec)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
cancel()
|
cancel()
|
||||||
|
|
||||||
var gotError bool
|
var gotError bool
|
||||||
for event := range eventChan {
|
for event := range streamResp.Events {
|
||||||
if event.Error != nil {
|
if event.Error != nil {
|
||||||
gotError = true
|
gotError = true
|
||||||
}
|
}
|
||||||
@@ -264,12 +316,12 @@ func TestClient_SendStream_SlowSSE(t *testing.T) {
|
|||||||
Body: []byte(`{}`),
|
Body: []byte(`{}`),
|
||||||
}
|
}
|
||||||
|
|
||||||
eventChan, err := client.SendStream(context.Background(), spec)
|
streamResp, err := client.SendStream(context.Background(), spec)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
var dataCount int
|
var dataCount int
|
||||||
var doneCount int
|
var doneCount int
|
||||||
for event := range eventChan {
|
for event := range streamResp.Events {
|
||||||
switch {
|
switch {
|
||||||
case event.Done:
|
case event.Done:
|
||||||
doneCount++
|
doneCount++
|
||||||
@@ -279,7 +331,7 @@ func TestClient_SendStream_SlowSSE(t *testing.T) {
|
|||||||
dataCount++
|
dataCount++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
assert.Equal(t, 1, dataCount, "expected exactly 1 data event from slow SSE")
|
assert.Equal(t, 2, dataCount, "expected 1 data frame plus DONE frame from slow SSE")
|
||||||
assert.Equal(t, 1, doneCount, "expected exactly 1 done event from slow SSE")
|
assert.Equal(t, 1, doneCount, "expected exactly 1 done event from slow SSE")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,19 +360,19 @@ func TestClient_SendStream_SplitSSEEvents(t *testing.T) {
|
|||||||
Body: []byte(`{}`),
|
Body: []byte(`{}`),
|
||||||
}
|
}
|
||||||
|
|
||||||
eventChan, err := client.SendStream(context.Background(), spec)
|
streamResp, err := client.SendStream(context.Background(), spec)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
var dataEvents int
|
var dataEvents int
|
||||||
var doneEvents int
|
var doneEvents int
|
||||||
for event := range eventChan {
|
for event := range streamResp.Events {
|
||||||
if event.Done {
|
if event.Done {
|
||||||
doneEvents++
|
doneEvents++
|
||||||
} else {
|
} else {
|
||||||
dataEvents++
|
dataEvents++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
assert.Equal(t, 2, dataEvents, "expected exactly 2 data events from split SSE")
|
assert.Equal(t, 3, dataEvents, "expected 2 data frames plus DONE frame from split SSE")
|
||||||
assert.Equal(t, 1, doneEvents)
|
assert.Equal(t, 1, doneEvents)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -397,11 +449,11 @@ func TestClient_SendStream_MidStreamNetworkError(t *testing.T) {
|
|||||||
Body: []byte(`{}`),
|
Body: []byte(`{}`),
|
||||||
}
|
}
|
||||||
|
|
||||||
eventChan, err := client.SendStream(context.Background(), spec)
|
streamResp, err := client.SendStream(context.Background(), spec)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
var gotData bool
|
var gotData bool
|
||||||
for event := range eventChan {
|
for event := range streamResp.Events {
|
||||||
if event.Error != nil {
|
if event.Error != nil {
|
||||||
} else if !event.Done {
|
} else if !event.Done {
|
||||||
gotData = true
|
gotData = true
|
||||||
|
|||||||
22
backend/pkg/buildinfo/buildinfo.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package buildinfo
|
||||||
|
|
||||||
|
var (
|
||||||
|
version = "dev"
|
||||||
|
commit = "unknown"
|
||||||
|
buildTime = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Version 返回构建注入的版本号。
|
||||||
|
func Version() string {
|
||||||
|
return version
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit 返回构建注入的 git commit。
|
||||||
|
func Commit() string {
|
||||||
|
return commit
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildTime 返回构建注入的构建时间。
|
||||||
|
func BuildTime() string {
|
||||||
|
return buildTime
|
||||||
|
}
|
||||||
17
backend/pkg/buildinfo/buildinfo_test.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package buildinfo
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestDefaults(t *testing.T) {
|
||||||
|
if Version() == "" {
|
||||||
|
t.Fatal("Version() 不应为空")
|
||||||
|
}
|
||||||
|
|
||||||
|
if Commit() == "" {
|
||||||
|
t.Fatal("Commit() 不应为空")
|
||||||
|
}
|
||||||
|
|
||||||
|
if BuildTime() == "" {
|
||||||
|
t.Fatal("BuildTime() 不应为空")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestLoadConfig_DefaultValues(t *testing.T) {
|
func TestLoadConfig_DefaultValues(t *testing.T) {
|
||||||
@@ -135,21 +136,7 @@ func TestLoadConfig_AutoCreate(t *testing.T) {
|
|||||||
|
|
||||||
func TestSaveAndLoadConfig(t *testing.T) {
|
func TestSaveAndLoadConfig(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
|
configPath := filepath.Join(tmpDir, "config.yaml")
|
||||||
homeDir, err := os.UserHomeDir()
|
|
||||||
require.NoError(t, err)
|
|
||||||
nexDir := filepath.Join(homeDir, ".nex")
|
|
||||||
configPath := filepath.Join(nexDir, "config.yaml")
|
|
||||||
|
|
||||||
originalConfig, err := os.ReadFile(configPath)
|
|
||||||
if err != nil && !os.IsNotExist(err) {
|
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if originalConfig != nil {
|
|
||||||
require.NoError(t, os.WriteFile(configPath, originalConfig, 0o600))
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
cfg := &config.Config{
|
cfg := &config.Config{
|
||||||
Server: config.ServerConfig{
|
Server: config.ServerConfig{
|
||||||
@@ -176,10 +163,13 @@ func TestSaveAndLoadConfig(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
err = config.SaveConfig(cfg)
|
data, err := yaml.Marshal(cfg)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
loaded, err := config.LoadConfig()
|
err = os.WriteFile(configPath, data, 0o600)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
loaded, err := config.LoadConfigFromPath(configPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
assert.Equal(t, cfg.Server.Port, loaded.Server.Port)
|
assert.Equal(t, cfg.Server.Port, loaded.Server.Port)
|
||||||
|
|||||||
@@ -184,7 +184,7 @@ func TestConversion_OpenAIToAnthropic_NonStream(t *testing.T) {
|
|||||||
body, _ := json.Marshal(openaiReq)
|
body, _ := json.Marshal(openaiReq)
|
||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -299,7 +299,7 @@ func TestConversion_OpenAIToOpenAI_Passthrough(t *testing.T) {
|
|||||||
body, _ := json.Marshal(reqBody)
|
body, _ := json.Marshal(reqBody)
|
||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -382,7 +382,7 @@ func TestConversion_OpenAIToAnthropic_Stream(t *testing.T) {
|
|||||||
body, _ := json.Marshal(openaiReq)
|
body, _ := json.Marshal(openaiReq)
|
||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -505,7 +505,7 @@ func TestConversion_ErrorResponse_Format(t *testing.T) {
|
|||||||
|
|
||||||
// OpenAI 协议格式
|
// OpenAI 协议格式
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
assert.True(t, w.Code >= 400)
|
assert.True(t, w.Code >= 400)
|
||||||
@@ -521,15 +521,14 @@ func TestConversion_OldRoutes_Return404(t *testing.T) {
|
|||||||
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"test"}`))
|
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"test"}`))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
// Gin 路由匹配但协议不支持返回 400
|
assert.Equal(t, 404, w.Code)
|
||||||
assert.Equal(t, 400, w.Code)
|
|
||||||
|
|
||||||
// 旧 Anthropic 路由
|
// 旧 Anthropic 路由
|
||||||
w = httptest.NewRecorder()
|
w = httptest.NewRecorder()
|
||||||
req = httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"test"}`))
|
req = httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"test"}`))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
assert.Equal(t, 400, w.Code)
|
assert.Equal(t, 404, w.Code)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============ Provider Protocol 字段测试 ============
|
// ============ Provider Protocol 字段测试 ============
|
||||||
|
|||||||
@@ -185,7 +185,7 @@ func TestE2E_OpenAI_NonStream_BasicText(t *testing.T) {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -243,7 +243,7 @@ func TestE2E_OpenAI_NonStream_MultiTurn(t *testing.T) {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -300,7 +300,7 @@ func TestE2E_OpenAI_NonStream_ToolCalls(t *testing.T) {
|
|||||||
"tool_choice": "auto",
|
"tool_choice": "auto",
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -343,7 +343,7 @@ func TestE2E_OpenAI_NonStream_MaxTokens_Length(t *testing.T) {
|
|||||||
"max_tokens": 30,
|
"max_tokens": 30,
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -379,7 +379,7 @@ func TestE2E_OpenAI_NonStream_UsageWithReasoning(t *testing.T) {
|
|||||||
"messages": []map[string]any{{"role": "user", "content": "15+23*2=?"}},
|
"messages": []map[string]any{{"role": "user", "content": "15+23*2=?"}},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -420,7 +420,7 @@ func TestE2E_OpenAI_NonStream_Refusal(t *testing.T) {
|
|||||||
"messages": []map[string]any{{"role": "user", "content": "做坏事"}},
|
"messages": []map[string]any{{"role": "user", "content": "做坏事"}},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -463,7 +463,7 @@ func TestE2E_OpenAI_Stream_Text(t *testing.T) {
|
|||||||
"stream": true,
|
"stream": true,
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -517,7 +517,7 @@ func TestE2E_OpenAI_Stream_ToolCalls(t *testing.T) {
|
|||||||
"stream": true,
|
"stream": true,
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -556,7 +556,7 @@ func TestE2E_OpenAI_Stream_WithUsage(t *testing.T) {
|
|||||||
"stream": true,
|
"stream": true,
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -980,7 +980,7 @@ func TestE2E_CrossProtocol_OpenAIToAnthropic_RequestFormat(t *testing.T) {
|
|||||||
"messages": []map[string]any{{"role": "user", "content": "Hello"}},
|
"messages": []map[string]any{{"role": "user", "content": "Hello"}},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1063,7 +1063,7 @@ func TestE2E_CrossProtocol_OpenAIToAnthropic_Stream(t *testing.T) {
|
|||||||
"stream": true,
|
"stream": true,
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1140,7 +1140,7 @@ func TestE2E_OpenAI_ErrorResponse(t *testing.T) {
|
|||||||
"messages": []map[string]any{{"role": "user", "content": "test"}},
|
"messages": []map[string]any{{"role": "user", "content": "test"}},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1225,7 +1225,7 @@ func TestE2E_OpenAI_NonStream_ParallelToolCalls(t *testing.T) {
|
|||||||
"tool_choice": "auto",
|
"tool_choice": "auto",
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1266,7 +1266,7 @@ func TestE2E_OpenAI_NonStream_StopSequence(t *testing.T) {
|
|||||||
"stop": []string{"5"},
|
"stop": []string{"5"},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1303,7 +1303,7 @@ func TestE2E_OpenAI_NonStream_ContentFilter(t *testing.T) {
|
|||||||
"messages": []map[string]any{{"role": "user", "content": "危险内容"}},
|
"messages": []map[string]any{{"role": "user", "content": "危险内容"}},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1586,7 +1586,7 @@ func TestE2E_CrossProtocol_OpenAIToAnthropic_NonStream_ToolCalls(t *testing.T) {
|
|||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1657,7 +1657,7 @@ func TestE2E_CrossProtocol_StopReasonMapping(t *testing.T) {
|
|||||||
"messages": []map[string]any{{"role": "user", "content": "长文"}},
|
"messages": []map[string]any{{"role": "user", "content": "长文"}},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1707,7 +1707,7 @@ func TestE2E_OpenAI_NonStream_AssistantWithToolResult(t *testing.T) {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1759,7 +1759,7 @@ func TestE2E_CrossProtocol_AnthropicToOpenAI_Stream_ToolCalls(t *testing.T) {
|
|||||||
"stream": true,
|
"stream": true,
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1835,7 +1835,7 @@ func TestE2E_OpenAI_Upstream5xx_ErrorPassthrough(t *testing.T) {
|
|||||||
"messages": []map[string]any{{"role": "user", "content": "test"}},
|
"messages": []map[string]any{{"role": "user", "content": "test"}},
|
||||||
})
|
})
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
req := httptest.NewRequest("POST", "/openai/chat/completions", bytes.NewReader(body))
|
req := httptest.NewRequest("POST", "/openai/v1/chat/completions", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
r.ServeHTTP(w, req)
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
@@ -1917,6 +1917,95 @@ func TestE2E_Anthropic_Stream_TruncatedSSE(t *testing.T) {
|
|||||||
assert.Contains(t, respBody, "正常")
|
assert.Contains(t, respBody, "正常")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestE2E_OpenAI_Models_LocalAggregation(t *testing.T) {
|
||||||
|
r, upstream := setupE2ETest(t)
|
||||||
|
e2eCreateProviderAndModel(t, r, "openai_p", "openai", "gpt-4o", upstream.URL)
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest("GET", "/openai/v1/models", nil)
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, w.Code)
|
||||||
|
var resp map[string]any
|
||||||
|
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||||
|
data, ok := resp["data"].([]any)
|
||||||
|
require.True(t, ok)
|
||||||
|
require.Len(t, data, 1)
|
||||||
|
model := data[0].(map[string]any)
|
||||||
|
assert.Equal(t, "openai_p/gpt-4o", model["id"])
|
||||||
|
assert.Equal(t, "openai_p", model["owned_by"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestE2E_OpenAI_Embeddings_SameProtocol(t *testing.T) {
|
||||||
|
r, upstream := setupE2ETest(t)
|
||||||
|
upstream.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||||
|
assert.Equal(t, "/embeddings", req.URL.Path)
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
"object": "list",
|
||||||
|
"data": []map[string]any{{
|
||||||
|
"index": 0,
|
||||||
|
"embedding": []float64{0.1, 0.2, 0.3},
|
||||||
|
}},
|
||||||
|
"model": "text-embedding-3-small",
|
||||||
|
"usage": map[string]any{
|
||||||
|
"prompt_tokens": 3,
|
||||||
|
"total_tokens": 3,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
e2eCreateProviderAndModel(t, r, "openai_p", "openai", "text-embedding-3-small", upstream.URL)
|
||||||
|
|
||||||
|
body, _ := json.Marshal(map[string]any{
|
||||||
|
"model": "openai_p/text-embedding-3-small",
|
||||||
|
"input": "hello",
|
||||||
|
})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest("POST", "/openai/v1/embeddings", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, w.Code)
|
||||||
|
var resp map[string]any
|
||||||
|
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||||
|
assert.Equal(t, "openai_p/text-embedding-3-small", resp["model"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestE2E_OpenAI_Rerank_SameProtocol(t *testing.T) {
|
||||||
|
r, upstream := setupE2ETest(t)
|
||||||
|
upstream.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||||
|
assert.Equal(t, "/rerank", req.URL.Path)
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
"results": []map[string]any{{
|
||||||
|
"index": 1,
|
||||||
|
"relevance_score": 0.98,
|
||||||
|
"document": "beta",
|
||||||
|
}},
|
||||||
|
"model": "rerank-v1",
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
e2eCreateProviderAndModel(t, r, "openai_p", "openai", "rerank-v1", upstream.URL)
|
||||||
|
|
||||||
|
body, _ := json.Marshal(map[string]any{
|
||||||
|
"model": "openai_p/rerank-v1",
|
||||||
|
"query": "second",
|
||||||
|
"documents": []string{"alpha", "beta"},
|
||||||
|
})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest("POST", "/openai/v1/rerank", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, w.Code)
|
||||||
|
var resp map[string]any
|
||||||
|
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||||
|
assert.Equal(t, "openai_p/rerank-v1", resp["model"])
|
||||||
|
results, ok := resp["results"].([]any)
|
||||||
|
require.True(t, ok)
|
||||||
|
require.Len(t, results, 1)
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
_ = fmt.Sprintf
|
_ = fmt.Sprintf
|
||||||
_ = time.Now
|
_ = time.Now
|
||||||
|
|||||||
@@ -59,10 +59,10 @@ func (mr *MockProviderClientMockRecorder) Send(ctx, spec any) *gomock.Call {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SendStream mocks base method.
|
// SendStream mocks base method.
|
||||||
func (m *MockProviderClient) SendStream(ctx context.Context, spec conversion.HTTPRequestSpec) (<-chan provider.StreamEvent, error) {
|
func (m *MockProviderClient) SendStream(ctx context.Context, spec conversion.HTTPRequestSpec) (*provider.StreamResponse, error) {
|
||||||
m.ctrl.T.Helper()
|
m.ctrl.T.Helper()
|
||||||
ret := m.ctrl.Call(m, "SendStream", ctx, spec)
|
ret := m.ctrl.Call(m, "SendStream", ctx, spec)
|
||||||
ret0, _ := ret[0].(<-chan provider.StreamEvent)
|
ret0, _ := ret[0].(*provider.StreamResponse)
|
||||||
ret1, _ := ret[1].(error)
|
ret1, _ := ret[1].(error)
|
||||||
return ret0, ret1
|
return ret0, ret1
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@
|
|||||||
|------|------|
|
|------|------|
|
||||||
| **完整 HTTP 接口体系转换** | 覆盖 /models、/embeddings、/rerank 等全部接口的 URL 路由映射、请求头转换、请求体/响应体格式转换 |
|
| **完整 HTTP 接口体系转换** | 覆盖 /models、/embeddings、/rerank 等全部接口的 URL 路由映射、请求头转换、请求体/响应体格式转换 |
|
||||||
| **输入输出解耦** | 客户端协议和服务端协议独立指定,任意组合 |
|
| **输入输出解耦** | 客户端协议和服务端协议独立指定,任意组合 |
|
||||||
| **同协议透传** | client == provider 时跳过转换,零语义损失、零序列化开销 |
|
| **同协议透传** | client == provider 时跳过 Canonical 全量转换,保持协议语义 |
|
||||||
| **尽力转换** | 能对接的参数尽可能对接,不能对接的各自忽略,保障最大覆盖面 |
|
| **尽力转换** | 能对接的参数尽可能对接,不能对接的各自忽略,保障最大覆盖面 |
|
||||||
| **协议可扩展** | 添加新协议只需实现 Adapter,不修改核心引擎 |
|
| **协议可扩展** | 添加新协议只需实现 Adapter,不修改核心引擎 |
|
||||||
| **流式优先** | SSE 流式转换作为核心能力,与非流式同等地位 |
|
| **流式优先** | SSE 流式转换作为核心能力,与非流式同等地位 |
|
||||||
@@ -75,8 +75,8 @@
|
|||||||
│ │ │ │
|
│ │ │ │
|
||||||
│ │ 入站: /{protocol}/{native_path} │ │
|
│ │ 入站: /{protocol}/{native_path} │ │
|
||||||
│ │ │ │
|
│ │ │ │
|
||||||
│ │ /<protocol_a>/v1/chat/completions → client=protocol_a, /v1/... │ │
|
│ │ /openai/v1/chat/completions → client=openai, /v1/chat/completions │ │
|
||||||
│ │ /<protocol_b>/v1/messages → client=protocol_b, /v1/... │ │
|
│ │ /anthropic/v1/messages → client=anthropic, /v1/messages │ │
|
||||||
│ │ │ │
|
│ │ │ │
|
||||||
│ │ Step 1: 识别 client protocol(URL 前缀 / 配置映射 / 任意方式) │ │
|
│ │ Step 1: 识别 client protocol(URL 前缀 / 配置映射 / 任意方式) │ │
|
||||||
│ │ Step 2: 剥离前缀 → 得到 nativePath │ │
|
│ │ Step 2: 剥离前缀 → 得到 nativePath │ │
|
||||||
@@ -112,17 +112,18 @@
|
|||||||
|
|
||||||
### 2.2 URL 路由规则
|
### 2.2 URL 路由规则
|
||||||
|
|
||||||
调用方负责识别协议并剥离前缀,将 `nativePath`、`clientProtocol`、`providerProtocol` 传入引擎。调用方可自行决定识别方式(URL 前缀、配置映射等)。
|
调用方负责识别协议并剥离前缀,将 `nativePath`、`clientProtocol`、`providerProtocol` 传入引擎。网关只剥离第一段协议前缀,不对剩余路径做版本号归一化;`/v1` 是否存在属于协议原生路径,由对应 ProtocolAdapter 按本地 API reference 识别和映射。
|
||||||
|
|
||||||
```
|
```
|
||||||
入站 URL 调用方剥离前缀后 引擎出站
|
入站 URL 调用方剥离前缀后 引擎出站
|
||||||
──────────────────────────────────────────────────────────────────────────────
|
──────────────────────────────────────────────────────────────────────────────
|
||||||
/<protocol_a>/v1/chat/completions → /v1/chat/completions → 目标协议路径
|
/openai/v1/chat/completions → /v1/chat/completions → /chat/completions
|
||||||
/<protocol_b>/v1/messages → /v1/messages → 目标协议路径
|
/openai/v1/models → /v1/models → /models
|
||||||
/<protocol_a>/v1/models → /v1/models → /v1/models(通常不变)
|
/anthropic/v1/messages → /v1/messages → /v1/messages
|
||||||
|
/anthropic/v1/models → /v1/models → /v1/models
|
||||||
```
|
```
|
||||||
|
|
||||||
出站到上游 API 时使用服务端协议原生路径(无前缀)。
|
出站到上游 API 时使用服务端协议原生路径(无网关协议前缀),并由 `provider.BaseURL + providerAdapter.BuildUrl(nativePath, interfaceType)` 组合得到真实 URL。OpenAI `base_url` 配置到版本路径一级(如 `https://api.openai.com/v1`),Anthropic `base_url` 配置到域名级(如 `https://api.anthropic.com`)。
|
||||||
|
|
||||||
### 2.3 请求处理流程
|
### 2.3 请求处理流程
|
||||||
|
|
||||||
@@ -146,14 +147,14 @@
|
|||||||
│ 响应处理 │ 原样返回 │ modelOverride非空时 │ Decode→modelOverride │
|
│ 响应处理 │ 原样返回 │ modelOverride非空时 │ Decode→modelOverride │
|
||||||
│ │ │ RewriteResponseModelName(body) │ →Encode │
|
│ │ │ RewriteResponseModelName(body) │ →Encode │
|
||||||
│ │ │ │ │
|
│ │ │ │ │
|
||||||
│ 流式处理 │ chunk→[chunk] │ chunk→RewriteResponseModelName │ Decode→Middleware │
|
│ 流式处理 │ raw SSE frame原样透传 │ SSE frame→仅改写data JSON中的model │ Decode→Middleware │
|
||||||
│ │ │ →[rewritten] │ →modelOverride→Encode │
|
│ │ 保留[DONE]和frame边界 │ 解析失败则输出原frame继续处理 │ →modelOverride→Encode │
|
||||||
│ │ │ │ │
|
│ │ │ │ │
|
||||||
│ 性能开销 │ 最低 │ 低(仅JSON字段改写) │ 高(完整序列化) │
|
│ 性能开销 │ 最低 │ 低(仅JSON字段改写) │ 高(完整序列化) │
|
||||||
└────────────────┴─────────────────────────┴────────────────────────────────────────┘
|
└────────────────┴─────────────────────────┴────────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
**智能透传的设计动机**:同协议场景下,若仅需改写 `model` 字段(如客户端请求模型 "X",上游需要模型 "Y"),无需完整解码/编码。直接在 JSON 层面手术式改写该字段,既保留原始请求的所有细节,又避免序列化开销。
|
**智能透传的设计动机**:同协议场景下,若仅需改写 `model` 字段(如客户端请求模型 "X",上游需要模型 "Y"),无需进入 Canonical 全量解码/编码。直接在 JSON 层面改写该字段,保持未改写字段的 JSON 内容和类型不变;实现不承诺保留原始字节顺序、空白或对象字段顺序。
|
||||||
|
|
||||||
#### 2.3.2 完整请求处理流程
|
#### 2.3.2 完整请求处理流程
|
||||||
|
|
||||||
@@ -162,7 +163,7 @@
|
|||||||
┌──────────────┐ ┌──────────────┐
|
┌──────────────┐ ┌──────────────┐
|
||||||
│ URL: │ 调用方完成: 1. 接口识别 │ URL: │
|
│ URL: │ 调用方完成: 1. 接口识别 │ URL: │
|
||||||
│ /<protocol>/ │ · clientProtocol 2. IsPassthrough? │ 目标协议 │
|
│ /<protocol>/ │ · clientProtocol 2. IsPassthrough? │ 目标协议 │
|
||||||
│ v1/... │ · nativePath ├─ yes ─┬─ 无 modelOverride → 透传车道 │ 原生路径 │
|
│ ... │ · nativePath ├─ yes ─┬─ 无 modelOverride → 透传车道 │ 原生路径 │
|
||||||
│ Headers: │ · providerProtocol │ └─ 有 modelOverride → 智能透传车道│ Headers: │
|
│ Headers: │ · providerProtocol │ └─ 有 modelOverride → 智能透传车道│ Headers: │
|
||||||
│ 协议原生格式 │ │ │ 目标协议格式 │
|
│ 协议原生格式 │ │ │ 目标协议格式 │
|
||||||
│ Body: │ └─ no → 完整转换车道 │ Body: │
|
│ Body: │ └─ no → 完整转换车道 │ Body: │
|
||||||
@@ -174,7 +175,7 @@
|
|||||||
|
|
||||||
**同协议透传**:client == provider 时,仅重建 Header 后原样转发到上游。
|
**同协议透传**:client == provider 时,仅重建 Header 后原样转发到上游。
|
||||||
**智能透传**:同协议且需改写 model 字段时,最小化 JSON 改写后转发。
|
**智能透传**:同协议且需改写 model 字段时,最小化 JSON 改写后转发。
|
||||||
**未知接口透传**:无法识别的路径,URL+Header 适配后 Body 原样转发。
|
**未知接口透传**:无法识别的路径,URL+Header 适配后 Body 原样转发;即使请求体存在顶层 `model`,也不做通用猜测。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -458,11 +459,13 @@ interface ProtocolAdapter {
|
|||||||
|
|
||||||
**`buildHeaders` 的设计**:Adapter 只需从 `provider` 中提取自己协议需要的认证和配置信息,构建自己的 Header 格式。不再需要理解其他协议的 Header。
|
**`buildHeaders` 的设计**:Adapter 只需从 `provider` 中提取自己协议需要的认证和配置信息,构建自己的 Header 格式。不再需要理解其他协议的 Header。
|
||||||
|
|
||||||
|
**URL 事实来源**:Adapter 的 `detectInterfaceType` 和 `buildUrl` 必须以本地 API reference 及网关对外协议契约为事实来源。OpenAI 对外路径为 `/openai/v1/...`,剥离协议前缀后的 nativePath 保留 `/v1`,例如 `/v1/chat/completions`、`/v1/models`、`/v1/embeddings`;但 OpenAI 供应商 `base_url` 配置到版本路径一级,`buildUrl` 输出上游 path 时移除 `/v1`,例如 `/chat/completions`、`/models`、`/embeddings`。Anthropic 参考 `docs/api_reference/anthropic`,nativePath 与上游 path 均保留 `/v1`,例如 `/v1/messages`、`/v1/models`。不得根据其他协议是否包含 `/v1` 推断当前协议路径。
|
||||||
|
|
||||||
**智能透传方法的契约**:
|
**智能透传方法的契约**:
|
||||||
- `rewriteRequestModelName` / `rewriteResponseModelName` 必须**幂等**(多次调用结果相同)
|
- `rewriteRequestModelName` / `rewriteResponseModelName` 必须**幂等**(多次调用结果相同)
|
||||||
- Rewrite 方法必须**最小化**(仅修改 model 字段,不触碰其他字段)
|
- Rewrite 方法必须**最小化**(仅修改 model 字段,不触碰其他字段)
|
||||||
- Rewrite 失败时,引擎使用宽容策略:记录警告日志,使用原始 body 继续处理
|
- Rewrite 失败时,引擎使用宽容策略:记录警告日志,使用原始 body 继续处理
|
||||||
- `extractModelName` 支持的接口类型:CHAT、EMBEDDINGS、RERANK(这些接口的请求体包含 model 字段)
|
- `extractModelName` 只支持 adapter 明确适配的接口类型:CHAT、EMBEDDINGS、RERANK(这些接口的请求体包含 model 字段)。PASSTHROUGH 或未适配接口返回错误或空结果,调用方按无 model 请求透传,不做顶层 `model` 猜测。
|
||||||
|
|
||||||
### 5.3 InterfaceType
|
### 5.3 InterfaceType
|
||||||
|
|
||||||
@@ -713,7 +716,7 @@ interface StreamConverter {
|
|||||||
| 转换器 | 触发条件 | processChunk | flush |
|
| 转换器 | 触发条件 | processChunk | flush |
|
||||||
|--------|---------|--------------|-------|
|
|--------|---------|--------------|-------|
|
||||||
| `PassthroughStreamConverter` | 同协议 + 无 modelOverride | `[rawChunk]` | `[]` |
|
| `PassthroughStreamConverter` | 同协议 + 无 modelOverride | `[rawChunk]` | `[]` |
|
||||||
| `SmartPassthroughStreamConverter` | 同协议 + 有 modelOverride | `[rewriteResponseModelName(rawChunk)]` | `[]` |
|
| `SmartPassthroughStreamConverter` | 同协议 + 有 modelOverride | 按 SSE frame 改写 `data` JSON 中的 model;失败输出原 frame | 输出缓存中的未完整 frame |
|
||||||
| `CanonicalStreamConverter` | 不同协议 | Decode→Middleware→modelOverride→Encode | decoder.flush()→encoder.flush() |
|
| `CanonicalStreamConverter` | 不同协议 | Decode→Middleware→modelOverride→Encode | decoder.flush()→encoder.flush() |
|
||||||
|
|
||||||
#### 6.3.3 PassthroughStreamConverter
|
#### 6.3.3 PassthroughStreamConverter
|
||||||
@@ -732,16 +735,30 @@ class SmartPassthroughStreamConverter implements StreamConverter {
|
|||||||
adapter: ProtocolAdapter
|
adapter: ProtocolAdapter
|
||||||
modelOverride: String
|
modelOverride: String
|
||||||
interfaceType: InterfaceType
|
interfaceType: InterfaceType
|
||||||
|
buffer: ByteArray
|
||||||
|
|
||||||
processChunk(rawChunk): Array<RawSSEChunk> {
|
processChunk(rawChunk): Array<RawSSEChunk> {
|
||||||
if rawChunk为空: return []
|
if rawChunk为空: return []
|
||||||
rewrittenChunk = adapter.rewriteResponseModelName(rawChunk, modelOverride, interfaceType)
|
buffer.append(rawChunk)
|
||||||
|
frames = splitCompleteSSEFrames(buffer)
|
||||||
|
result = []
|
||||||
|
for frame in frames:
|
||||||
|
payload = extractDataPayload(frame)
|
||||||
|
if payload == "[DONE]":
|
||||||
|
result.append(frame)
|
||||||
|
continue
|
||||||
|
rewrittenPayload = adapter.rewriteResponseModelName(payload, modelOverride, interfaceType)
|
||||||
if rewrite失败:
|
if rewrite失败:
|
||||||
log.warn("智能透传改写失败,使用原始 chunk")
|
log.warn("智能透传改写失败,使用原始 SSE frame")
|
||||||
return [rawChunk]
|
result.append(frame)
|
||||||
return [rewrittenChunk]
|
else:
|
||||||
|
result.append(rebuildSSEFrameWithData(frame, rewrittenPayload))
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
flush(): Array<RawSSEChunk> {
|
||||||
|
if buffer为空: return []
|
||||||
|
return [buffer.drain()] // 未完整 frame 原样输出
|
||||||
}
|
}
|
||||||
flush(): Array<RawSSEChunk> { return [] }
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -794,7 +811,9 @@ function createStreamConverter(clientProtocol, providerProtocol, modelOverride,
|
|||||||
if isPassthrough(clientProtocol, providerProtocol):
|
if isPassthrough(clientProtocol, providerProtocol):
|
||||||
if modelOverride非空:
|
if modelOverride非空:
|
||||||
adapter = registry.get(clientProtocol)
|
adapter = registry.get(clientProtocol)
|
||||||
|
// 解析 SSE frame,仅改写 data JSON 中的 model;解析失败输出原 frame
|
||||||
return new SmartPassthroughStreamConverter(adapter, modelOverride, interfaceType)
|
return new SmartPassthroughStreamConverter(adapter, modelOverride, interfaceType)
|
||||||
|
// raw passthrough 保留 SSE frame 边界和 [DONE]
|
||||||
return new PassthroughStreamConverter()
|
return new PassthroughStreamConverter()
|
||||||
|
|
||||||
providerAdapter = registry.get(providerProtocol)
|
providerAdapter = registry.get(providerProtocol)
|
||||||
@@ -881,7 +900,7 @@ converter.flush()
|
|||||||
|
|
||||||
// 场景6: 同协议流式智能透传
|
// 场景6: 同协议流式智能透传
|
||||||
converter = engine.createStreamConverter("openai", "openai", "gpt-4-turbo", CHAT)
|
converter = engine.createStreamConverter("openai", "openai", "gpt-4-turbo", CHAT)
|
||||||
// 使用 SmartPassthroughStreamConverter,逐 chunk 改写 model 字段
|
// 使用 SmartPassthroughStreamConverter,按 SSE frame 改写 data JSON 中的 model 字段
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -894,10 +913,10 @@ converter = engine.createStreamConverter("openai", "openai", "gpt-4-turbo", CHAT
|
|||||||
上游 SSE 流
|
上游 SSE 流
|
||||||
│
|
│
|
||||||
├─ 同协议 + 无 modelOverride: PassthroughStreamConverter
|
├─ 同协议 + 无 modelOverride: PassthroughStreamConverter
|
||||||
│ chunk → [chunk]
|
│ raw SSE frame → [raw SSE frame]
|
||||||
│
|
│
|
||||||
├─ 同协议 + 有 modelOverride: SmartPassthroughStreamConverter
|
├─ 同协议 + 有 modelOverride: SmartPassthroughStreamConverter
|
||||||
│ chunk → [rewriteResponseModelName(chunk)]
|
│ SSE frame → data JSON model rewrite → [SSE frame]
|
||||||
│
|
│
|
||||||
└─ 不同协议: CanonicalStreamConverter
|
└─ 不同协议: CanonicalStreamConverter
|
||||||
StreamDecoder StreamEncoder
|
StreamDecoder StreamEncoder
|
||||||
@@ -1025,7 +1044,8 @@ ErrorCode = Enum<
|
|||||||
UTF8_DECODE_ERROR, // UTF-8 解码错误
|
UTF8_DECODE_ERROR, // UTF-8 解码错误
|
||||||
PROTOCOL_CONSTRAINT_VIOLATION, // 违反协议约束
|
PROTOCOL_CONSTRAINT_VIOLATION, // 违反协议约束
|
||||||
ENCODING_FAILURE, // 编码失败
|
ENCODING_FAILURE, // 编码失败
|
||||||
INTERFACE_NOT_SUPPORTED // 目标协议不支持此接口
|
INTERFACE_NOT_SUPPORTED, // 目标协议不支持此接口
|
||||||
|
UNSUPPORTED_MULTIMODAL // 多模态内容块暂不支持跨协议转换
|
||||||
>
|
>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1050,7 +1070,7 @@ ErrorCode = Enum<
|
|||||||
│ │ - interceptStreamEvent 返回 error → continue │
|
│ │ - interceptStreamEvent 返回 error → continue │
|
||||||
├─────────────────┼───────────────────────────────────────────────────┤
|
├─────────────────┼───────────────────────────────────────────────────┤
|
||||||
│ 智能透传 │ 宽容模式:重写失败则使用原始 body/chunk │
|
│ 智能透传 │ 宽容模式:重写失败则使用原始 body/chunk │
|
||||||
│ │ - Rewrite 失败 → log.warn + 返回原始 body/chunk │
|
│ │ - Rewrite 失败 → log.warn + 返回原始 body/SSE frame│
|
||||||
├─────────────────┼───────────────────────────────────────────────────┤
|
├─────────────────┼───────────────────────────────────────────────────┤
|
||||||
│ 请求中间件 │ 严格模式:返回错误则中断整个转换 │
|
│ 请求中间件 │ 严格模式:返回错误则中断整个转换 │
|
||||||
│ │ - intercept 返回 error → 返回 error │
|
│ │ - intercept 返回 error → 返回 error │
|
||||||
@@ -1072,11 +1092,24 @@ ErrorCode = Enum<
|
|||||||
|
|
||||||
具体策略由 `supportsInterface` 返回值决定:返回 false 时引擎直接透传 body。
|
具体策略由 `supportsInterface` 返回值决定:返回 false 时引擎直接透传 body。
|
||||||
|
|
||||||
|
**多模态处理**(`UNSUPPORTED_MULTIMODAL`):Canonical Model 保留 image、audio、video、file 内容块占位,但当前跨协议多模态编解码暂未实现。跨协议完整转换遇到这些内容块时返回 `UNSUPPORTED_MULTIMODAL`;同协议 raw passthrough 和 smart passthrough 不拒绝多模态字段,仍按原协议请求透传或仅改写 model。
|
||||||
|
|
||||||
### 9.3 错误响应格式
|
### 9.3 错误响应格式
|
||||||
|
|
||||||
转换失败时,错误响应用**客户端协议(client protocol)**的格式编码。由 `clientAdapter.encodeError(error)` 完成。各协议的错误响应 JSON 结构和 HTTP 状态码映射详见各自的协议适配文档(附录 E)。
|
ConversionEngine 的 `encodeError` 是协议 Adapter 的错误编码能力,用于 SDK 内部或非代理场景把 `ConversionError` 编码为客户端协议格式。各协议的错误响应 JSON 结构和 HTTP 状态码映射详见各自的协议适配文档(附录 E)。
|
||||||
|
|
||||||
Middleware 中断转换时同理,引擎调用 clientAdapter.encodeError 将 ConversionError 编码为客户端可理解的格式。
|
ProxyHandler 对外遵循更明确的代理错误边界:
|
||||||
|
|
||||||
|
| 场景 | 响应策略 |
|
||||||
|
|------|---------|
|
||||||
|
| 网关层错误 | 返回应用统一 JSON:`{"error": "...", "code": "..."}` |
|
||||||
|
| 上游已返回 HTTP 非 2xx | 透传上游 status、过滤 hop-by-hop 后的 headers、body |
|
||||||
|
| 未收到上游 HTTP 响应 | 返回 `UPSTREAM_UNAVAILABLE`,HTTP 502 |
|
||||||
|
| 网关层 JSON 解析失败 | 返回 `INVALID_JSON`,HTTP 400 |
|
||||||
|
| 路由统一模型失败 | 返回 `MODEL_NOT_FOUND`,HTTP 404 |
|
||||||
|
| 跨协议转换失败 | 返回 `CONVERSION_FAILED` 或具体转换错误码 |
|
||||||
|
|
||||||
|
因此,代理接口中的网关层错误不会再编码成 OpenAI/Anthropic 协议错误格式;只有上游已经返回的错误响应才按上游原样透传。
|
||||||
|
|
||||||
#### 9.3.1 EncodeError Fallback 行为
|
#### 9.3.1 EncodeError Fallback 行为
|
||||||
|
|
||||||
@@ -1179,7 +1212,7 @@ ProtocolAdapter
|
|||||||
// ─── 流式处理 ───
|
// ─── 流式处理 ───
|
||||||
StreamConverter: .processChunk(raw) / .flush()
|
StreamConverter: .processChunk(raw) / .flush()
|
||||||
├─ PassthroughStreamConverter [raw] → [raw]
|
├─ PassthroughStreamConverter [raw] → [raw]
|
||||||
├─ SmartPassthroughStreamConverter [raw] → [rewrite(raw)]
|
├─ SmartPassthroughStreamConverter [SSE frame] → [rewrite(data JSON)]
|
||||||
└─ CanonicalStreamConverter decode → middleware → modelOverride → encode
|
└─ CanonicalStreamConverter decode → middleware → modelOverride → encode
|
||||||
|
|
||||||
// ─── 中间件 ───
|
// ─── 中间件 ───
|
||||||
@@ -1248,7 +1281,7 @@ Canonical Model 是**活的公共契约**,不是固定不变的。其字段集
|
|||||||
- `decodeXxxRequest` / `encodeXxxRequest`:扩展层接口仅在 `supportsInterface` 返回 true 时被调用(§6.2 convertBody 分支);返回 false 时引擎直接透传 body
|
- `decodeXxxRequest` / `encodeXxxRequest`:扩展层接口仅在 `supportsInterface` 返回 true 时被调用(§6.2 convertBody 分支);返回 false 时引擎直接透传 body
|
||||||
- `createStreamDecoder` / `createStreamEncoder`:引擎在 `createStreamConverter` 中调用(§6.1),Decoder 来自 provider 协议(解码上游 SSE),Encoder 来自 client 协议(编码给客户端)
|
- `createStreamDecoder` / `createStreamEncoder`:引擎在 `createStreamConverter` 中调用(§6.1),Decoder 来自 provider 协议(解码上游 SSE),Encoder 来自 client 协议(编码给客户端)
|
||||||
- `buildHeaders`:每次请求出站时调用,同协议透传也会调用
|
- `buildHeaders`:每次请求出站时调用,同协议透传也会调用
|
||||||
- `encodeError`:转换失败或 Middleware 中断时调用,使用 client 协议格式编码错误响应
|
- `encodeError`:转换失败或 Middleware 中断时的协议错误编码能力;ProxyHandler 的网关层错误使用应用统一格式,不调用协议错误编码
|
||||||
|
|
||||||
### D.1 协议基本信息
|
### D.1 协议基本信息
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
| -------- | ----------------------------------- |
|
| -------- | ----------------------------------- |
|
||||||
| 协议名称 | `"openai"` |
|
| 协议名称 | `"openai"` |
|
||||||
| 协议版本 | 无固定版本头,API 持续演进 |
|
| 协议版本 | 无固定版本头,API 持续演进 |
|
||||||
| Base URL | `https://api.openai.com` |
|
| Base URL | `https://api.openai.com/v1`(供应商配置到版本路径一级) |
|
||||||
| 认证方式 | `Authorization: Bearer <api_key>` |
|
| 认证方式 | `Authorization: Bearer <api_key>` |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -47,13 +47,13 @@
|
|||||||
OpenAI.detectInterfaceType(nativePath):
|
OpenAI.detectInterfaceType(nativePath):
|
||||||
if nativePath == "/v1/chat/completions": return CHAT
|
if nativePath == "/v1/chat/completions": return CHAT
|
||||||
if nativePath == "/v1/models": return MODELS
|
if nativePath == "/v1/models": return MODELS
|
||||||
if nativePath matches "^/v1/models/[^/]+$": return MODEL_INFO
|
if nativePath startsWith "/v1/models/" and suffix is not empty: return MODEL_INFO
|
||||||
if nativePath == "/v1/embeddings": return EMBEDDINGS
|
if nativePath == "/v1/embeddings": return EMBEDDINGS
|
||||||
if nativePath == "/v1/rerank": return RERANK
|
if nativePath == "/v1/rerank": return RERANK
|
||||||
return PASSTHROUGH
|
return PASSTHROUGH
|
||||||
```
|
```
|
||||||
|
|
||||||
**说明**:`detectInterfaceType` 由 OpenAI Adapter 实现,根据 OpenAI 协议的 URL 路径约定识别接口类型。
|
**说明**:`detectInterfaceType` 由 OpenAI Adapter 实现,根据 OpenAI 协议的 URL 路径约定识别接口类型。网关剥离 `/openai` 协议前缀后,OpenAI Adapter 接收的 nativePath 保留 `/v1`。
|
||||||
|
|
||||||
### 2.3 接口能力矩阵
|
### 2.3 接口能力矩阵
|
||||||
|
|
||||||
@@ -74,14 +74,16 @@ OpenAI.supportsInterface(type):
|
|||||||
```
|
```
|
||||||
OpenAI.buildUrl(nativePath, interfaceType):
|
OpenAI.buildUrl(nativePath, interfaceType):
|
||||||
switch interfaceType:
|
switch interfaceType:
|
||||||
case CHAT: return "/v1/chat/completions"
|
case CHAT: return "/chat/completions"
|
||||||
case MODELS: return "/v1/models"
|
case MODELS: return "/models"
|
||||||
case MODEL_INFO: return "/v1/models/{modelId}"
|
case MODEL_INFO: return "/models/{modelId}"
|
||||||
case EMBEDDINGS: return "/v1/embeddings"
|
case EMBEDDINGS: return "/embeddings"
|
||||||
case RERANK: return "/v1/rerank"
|
case RERANK: return "/rerank"
|
||||||
default: return nativePath
|
default: return nativePath
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**说明**:OpenAI 供应商 `base_url` 配置到版本路径一级,`buildUrl` 输出上游 path 时移除 nativePath 中的 `/v1`,避免拼接出重复版本段。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. 请求头构建
|
## 3. 请求头构建
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
VITE_API_BASE=
|
VITE_API_BASE=
|
||||||
|
VITE_APP_VERSION=0.1.2
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
VITE_API_BASE=
|
VITE_API_BASE=
|
||||||
|
VITE_APP_VERSION=0.1.2
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
VITE_API_BASE=/api
|
VITE_API_BASE=/api
|
||||||
|
VITE_APP_VERSION=0.1.2
|
||||||
|
|||||||
4
frontend/.gitignore
vendored
@@ -10,6 +10,10 @@ lerna-debug.log*
|
|||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
dist-ssr
|
dist-ssr
|
||||||
|
coverage
|
||||||
|
playwright-report
|
||||||
|
test-results
|
||||||
|
*.tsbuildinfo
|
||||||
*.local
|
*.local
|
||||||
|
|
||||||
# Editor directories and files
|
# Editor directories and files
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
dist-ssr
|
dist-ssr
|
||||||
|
playwright-report
|
||||||
|
test-results
|
||||||
bun.lock
|
bun.lock
|
||||||
package-lock.json
|
package-lock.json
|
||||||
yarn.lock
|
yarn.lock
|
||||||
@@ -8,6 +10,8 @@ pnpm-lock.yaml
|
|||||||
.env.*
|
.env.*
|
||||||
*.local
|
*.local
|
||||||
coverage
|
coverage
|
||||||
|
*.tsbuildinfo
|
||||||
|
.DS_Store
|
||||||
**/*.snap
|
**/*.snap
|
||||||
**/__snapshots__/**
|
**/__snapshots__/**
|
||||||
*.svg
|
*.svg
|
||||||
|
|||||||
3
frontend/.vscode/extensions.json
vendored
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]
|
|
||||||
}
|
|
||||||
7
frontend/.vscode/settings.json
vendored
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"editor.formatOnSave": true,
|
|
||||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
|
||||||
"editor.codeActionsOnSave": {
|
|
||||||
"source.fixAll.eslint": "explicit"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# AI Gateway Frontend
|
# Nex Frontend
|
||||||
|
|
||||||
AI 网关管理前端,提供供应商配置和用量统计界面。
|
AI 网关管理前端,提供供应商配置和用量统计界面。
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ AI 网关管理前端,提供供应商配置和用量统计界面。
|
|||||||
- **UI 组件库**: TDesign
|
- **UI 组件库**: TDesign
|
||||||
- **路由**: React Router v7
|
- **路由**: React Router v7
|
||||||
- **数据获取**: TanStack Query v5
|
- **数据获取**: TanStack Query v5
|
||||||
- **样式**: SCSS Modules(禁止使用纯 CSS)
|
- **样式**: TDesign 组件 props 优先,TDesign tokens 次之,SCSS 作为兜底补充
|
||||||
- **测试**: Vitest + React Testing Library + Playwright
|
- **测试**: Vitest + React Testing Library + Playwright
|
||||||
- **代码格式化**: Prettier
|
- **代码格式化**: Prettier
|
||||||
|
|
||||||
@@ -86,17 +86,20 @@ frontend/
|
|||||||
│ │ ├── client.ts # 统一 request<T>() + 字段转换
|
│ │ ├── client.ts # 统一 request<T>() + 字段转换
|
||||||
│ │ ├── providers.ts # Provider CRUD
|
│ │ ├── providers.ts # Provider CRUD
|
||||||
│ │ ├── models.ts # Model CRUD
|
│ │ ├── models.ts # Model CRUD
|
||||||
│ │ └── stats.ts # Stats 查询
|
│ │ ├── stats.ts # Stats 查询
|
||||||
|
│ │ └── version.ts # 后端版本查询
|
||||||
│ ├── components/
|
│ ├── components/
|
||||||
│ │ └── AppLayout/ # 侧边栏导航布局
|
│ │ └── AppLayout/ # 侧边栏导航布局
|
||||||
│ ├── hooks/ # TanStack Query hooks
|
│ ├── hooks/ # TanStack Query hooks
|
||||||
│ │ ├── useProviders.ts
|
│ │ ├── useProviders.ts
|
||||||
│ │ ├── useModels.ts
|
│ │ ├── useModels.ts
|
||||||
│ │ └── useStats.ts
|
│ │ ├── useStats.ts
|
||||||
|
│ │ └── useVersion.ts
|
||||||
│ ├── pages/
|
│ ├── pages/
|
||||||
│ │ ├── Providers/ # 供应商管理(含内嵌模型管理)
|
│ │ ├── Providers/ # 供应商管理(含内嵌模型管理)
|
||||||
│ │ ├── Stats/ # 用量统计
|
│ │ ├── Stats/ # 用量统计
|
||||||
│ │ ├── Settings/ # 设置(开发中)
|
│ │ ├── Settings/ # 设置(开发中)
|
||||||
|
│ │ ├── About/ # 关于页面(品牌与版本信息)
|
||||||
│ │ └── NotFound.tsx
|
│ │ └── NotFound.tsx
|
||||||
│ ├── routes/
|
│ ├── routes/
|
||||||
│ │ └── index.tsx # 路由配置
|
│ │ └── index.tsx # 路由配置
|
||||||
@@ -111,6 +114,7 @@ frontend/
|
|||||||
│ ├── main.tsx
|
│ ├── main.tsx
|
||||||
│ └── index.scss
|
│ └── index.scss
|
||||||
├── e2e/ # Playwright E2E 测试
|
├── e2e/ # Playwright E2E 测试
|
||||||
|
├── public/ # 静态资源(icon.png 来源于 ../assets/icon.png)
|
||||||
├── vitest.config.ts
|
├── vitest.config.ts
|
||||||
├── playwright.config.ts
|
├── playwright.config.ts
|
||||||
├── tsconfig.json
|
├── tsconfig.json
|
||||||
@@ -200,6 +204,12 @@ bun run test:e2e
|
|||||||
- 按模型筛选
|
- 按模型筛选
|
||||||
- 按日期范围筛选(DatePicker.RangePicker)
|
- 按日期范围筛选(DatePicker.RangePicker)
|
||||||
|
|
||||||
|
### 关于页面
|
||||||
|
|
||||||
|
- 展示应用名称、产品描述和项目链接
|
||||||
|
- 展示前端版本、后端版本、后端 commit 和构建时间
|
||||||
|
- 根据 `VITE_APP_VERSION` 与 `GET /api/version` 返回值提示前后端版本是否一致
|
||||||
|
|
||||||
## 测试策略
|
## 测试策略
|
||||||
|
|
||||||
### 目录结构
|
### 目录结构
|
||||||
@@ -232,8 +242,9 @@ __tests__/
|
|||||||
## 环境变量
|
## 环境变量
|
||||||
|
|
||||||
| 变量 | 开发环境 | 生产环境 | 说明 |
|
| 变量 | 开发环境 | 生产环境 | 说明 |
|
||||||
| --------------- | -------- | -------- | ------------------------------- |
|
| ------------------ | -------- | -------- | ----------------------------------------- |
|
||||||
| `VITE_API_BASE` | (空) | `/api` | API 基础路径,空则走 Vite proxy |
|
| `VITE_API_BASE` | (空) | `/api` | API 基础路径,空则走 Vite proxy |
|
||||||
|
| `VITE_APP_VERSION` | `0.1.0` | `0.1.0` | 前端构建版本,由 `make version-sync` 同步 |
|
||||||
|
|
||||||
**E2E 测试特有**:
|
**E2E 测试特有**:
|
||||||
|
|
||||||
@@ -242,9 +253,11 @@ __tests__/
|
|||||||
|
|
||||||
## 开发规范
|
## 开发规范
|
||||||
|
|
||||||
- 所有样式使用 SCSS,禁止使用纯 CSS 文件
|
- 样式优先使用 TDesign 组件 props(如 `hoverShadow`、`headerBordered`、`variant`、`shape`、`gutter`)
|
||||||
- 组件级样式使用 SCSS Modules(\*.module.scss)
|
- 组件 props 无法表达时使用 TDesign tokens(`var(--td-*)`)
|
||||||
|
- 仅当 props 和 tokens 无法满足布局、响应式或品牌视觉需求时使用 SCSS,禁止使用纯 CSS 文件
|
||||||
- 图标优先使用 TDesign 图标(tdesign-icons-react)
|
- 图标优先使用 TDesign 图标(tdesign-icons-react)
|
||||||
|
- 应用 favicon 使用 `frontend/public/icon.png`,该文件来源于仓库根目录 `assets/icon.png`
|
||||||
- TypeScript strict 模式,禁止 any 类型
|
- TypeScript strict 模式,禁止 any 类型
|
||||||
- API 层自动处理 snake_case ↔ camelCase 字段转换
|
- API 层自动处理 snake_case ↔ camelCase 字段转换
|
||||||
- 使用路径别名 `@/` 引用 src 目录
|
- 使用路径别名 `@/` 引用 src 目录
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ test.describe('侧边栏', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('应显示应用名称', async ({ page }) => {
|
test('应显示应用名称', async ({ page }) => {
|
||||||
await expect(page.locator('aside').getByText('AI Gateway')).toBeVisible()
|
await expect(page.locator('aside').getByText('Nex')).toBeVisible()
|
||||||
})
|
})
|
||||||
|
|
||||||
test('应显示导航菜单项', async ({ page }) => {
|
test('应显示导航菜单项', async ({ page }) => {
|
||||||
@@ -41,6 +41,15 @@ test.describe('页面导航', () => {
|
|||||||
await expect(page.getByRole('heading', { name: '供应商管理' })).toBeVisible()
|
await expect(page.getByRole('heading', { name: '供应商管理' })).toBeVisible()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('应能切换到关于页面并显示版本信息', async ({ page }) => {
|
||||||
|
await page.locator('aside').getByText('关于').click()
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: '关于' })).toBeVisible()
|
||||||
|
await expect(page.getByRole('heading', { name: 'Nex' })).toBeVisible()
|
||||||
|
await expect(page.getByText('前端版本')).toBeVisible()
|
||||||
|
await expect(page.getByText('后端版本')).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
test('应在刷新后保持当前页面', async ({ page }) => {
|
test('应在刷新后保持当前页面', async ({ page }) => {
|
||||||
await page.locator('aside').getByText('用量统计').click()
|
await page.locator('aside').getByText('用量统计').click()
|
||||||
await expect(page.getByRole('heading', { name: '用量统计' })).toBeVisible()
|
await expect(page.getByRole('heading', { name: '用量统计' })).toBeVisible()
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import localRules from './eslint-rules/index.js'
|
|||||||
import eslintConfigPrettier from 'eslint-config-prettier'
|
import eslintConfigPrettier from 'eslint-config-prettier'
|
||||||
|
|
||||||
export default tseslint.config(
|
export default tseslint.config(
|
||||||
{ ignores: ['dist'] },
|
{ ignores: ['dist', 'coverage', 'playwright-report', 'test-results', '*.tsbuildinfo'] },
|
||||||
...tanstackQuery.configs['flat/recommended'],
|
...tanstackQuery.configs['flat/recommended'],
|
||||||
{
|
{
|
||||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
<html lang="zh-CN">
|
<html lang="zh-CN">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/png" href="/icon.png" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>AI Gateway</title>
|
<title>Nex</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.1.2",
|
||||||
|
"license": "Apache-2.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 9.3 KiB |
BIN
frontend/public/icon.png
LFS
Normal file
@@ -1,24 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg">
|
|
||||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
|
||||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
|
||||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
|
||||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
|
||||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
|
||||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
|
||||||
</symbol>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 4.9 KiB |
30
frontend/src/__tests__/api/version.test.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { http, HttpResponse } from 'msw'
|
||||||
|
import { setupServer } from 'msw/node'
|
||||||
|
import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest'
|
||||||
|
import { getBackendVersion } from '@/api/version'
|
||||||
|
|
||||||
|
describe('version API', () => {
|
||||||
|
const server = setupServer()
|
||||||
|
|
||||||
|
beforeAll(() => server.listen({ onUnhandledRequest: 'bypass' }))
|
||||||
|
afterEach(() => server.resetHandlers())
|
||||||
|
afterAll(() => server.close())
|
||||||
|
|
||||||
|
it('fetches backend version and converts build_time to buildTime', async () => {
|
||||||
|
server.use(
|
||||||
|
http.get('http://localhost:3000/api/version', () => {
|
||||||
|
return HttpResponse.json({
|
||||||
|
version: '0.1.0',
|
||||||
|
commit: 'abc1234',
|
||||||
|
build_time: '2026-05-05T00:00:00Z',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
await expect(getBackendVersion()).resolves.toEqual({
|
||||||
|
version: '0.1.0',
|
||||||
|
commit: 'abc1234',
|
||||||
|
buildTime: '2026-05-05T00:00:00Z',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,25 +1,37 @@
|
|||||||
import { render, screen } from '@testing-library/react'
|
import { render, screen } from '@testing-library/react'
|
||||||
import { BrowserRouter } from 'react-router'
|
import userEvent from '@testing-library/user-event'
|
||||||
|
import { MemoryRouter } from 'react-router'
|
||||||
import { describe, it, expect } from 'vitest'
|
import { describe, it, expect } from 'vitest'
|
||||||
import { AppLayout } from '@/components/AppLayout'
|
import { AppLayout } from '@/components/AppLayout'
|
||||||
|
|
||||||
const renderWithRouter = (component: React.ReactNode) => {
|
const renderWithRouter = (component: React.ReactNode) => {
|
||||||
return render(<BrowserRouter>{component}</BrowserRouter>)
|
return render(<MemoryRouter initialEntries={['/providers']}>{component}</MemoryRouter>)
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('AppLayout', () => {
|
describe('AppLayout', () => {
|
||||||
it('renders sidebar with app name', () => {
|
it('renders sidebar with app name', () => {
|
||||||
renderWithRouter(<AppLayout />)
|
renderWithRouter(<AppLayout />)
|
||||||
|
|
||||||
const appNames = screen.getAllByText('AI Gateway')
|
expect(screen.getByText('Nex')).toBeInTheDocument()
|
||||||
expect(appNames.length).toBeGreaterThan(0)
|
expect(screen.getByAltText('Nex logo')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps logo visible when sidebar is collapsed', async () => {
|
||||||
|
const user = userEvent.setup()
|
||||||
|
renderWithRouter(<AppLayout />)
|
||||||
|
|
||||||
|
await user.click(screen.getByLabelText('收起侧边栏'))
|
||||||
|
|
||||||
|
expect(screen.getByAltText('Nex logo')).toBeInTheDocument()
|
||||||
|
expect(screen.queryByText('Nex')).not.toBeInTheDocument()
|
||||||
|
expect(screen.getByLabelText('展开侧边栏')).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('renders navigation menu items', () => {
|
it('renders navigation menu items', () => {
|
||||||
renderWithRouter(<AppLayout />)
|
renderWithRouter(<AppLayout />)
|
||||||
|
|
||||||
expect(screen.getByText('供应商管理')).toBeInTheDocument()
|
expect(screen.getAllByText('供应商管理').length).toBeGreaterThan(0)
|
||||||
expect(screen.getByText('用量统计')).toBeInTheDocument()
|
expect(screen.getAllByText('用量统计').length).toBeGreaterThan(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('renders settings menu item', () => {
|
it('renders settings menu item', () => {
|
||||||
@@ -28,6 +40,12 @@ describe('AppLayout', () => {
|
|||||||
expect(screen.getByText('设置')).toBeInTheDocument()
|
expect(screen.getByText('设置')).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('renders about menu item', () => {
|
||||||
|
renderWithRouter(<AppLayout />)
|
||||||
|
|
||||||
|
expect(screen.getByText('关于')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
it('renders content outlet', () => {
|
it('renders content outlet', () => {
|
||||||
const { container } = renderWithRouter(<AppLayout />)
|
const { container } = renderWithRouter(<AppLayout />)
|
||||||
|
|
||||||
|
|||||||
33
frontend/src/__tests__/hooks/useVersion.test.tsx
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||||
|
import { renderHook, waitFor } from '@testing-library/react'
|
||||||
|
import { http, HttpResponse } from 'msw'
|
||||||
|
import { setupServer } from 'msw/node'
|
||||||
|
import React from 'react'
|
||||||
|
import { useBackendVersion } from '@/hooks/useVersion'
|
||||||
|
|
||||||
|
const server = setupServer(
|
||||||
|
http.get('/api/version', () => {
|
||||||
|
return HttpResponse.json({ version: '0.1.0', commit: 'abc1234', build_time: '2026-05-05T00:00:00Z' })
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
function createWrapper() {
|
||||||
|
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||||
|
return function Wrapper({ children }: { children: React.ReactNode }) {
|
||||||
|
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => server.listen())
|
||||||
|
afterEach(() => server.resetHandlers())
|
||||||
|
afterAll(() => server.close())
|
||||||
|
|
||||||
|
describe('useBackendVersion', () => {
|
||||||
|
it('fetches backend version', async () => {
|
||||||
|
const { result } = renderHook(() => useBackendVersion(), { wrapper: createWrapper() })
|
||||||
|
|
||||||
|
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||||
|
|
||||||
|
expect(result.current.data).toEqual({ version: '0.1.0', commit: 'abc1234', buildTime: '2026-05-05T00:00:00Z' })
|
||||||
|
})
|
||||||
|
})
|
||||||
88
frontend/src/__tests__/pages/About.test.tsx
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { render, screen } from '@testing-library/react'
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { useBackendVersion } from '@/hooks/useVersion'
|
||||||
|
import AboutPage from '@/pages/About'
|
||||||
|
|
||||||
|
vi.mock('@/hooks/useVersion', () => ({
|
||||||
|
useBackendVersion: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/constants/app', () => ({
|
||||||
|
APP_NAME: 'Nex',
|
||||||
|
APP_DESCRIPTION: 'AI Gateway - 统一的大模型 API 网关',
|
||||||
|
APP_WEBSITE: 'https://github.com/nex/gateway',
|
||||||
|
APP_VERSION: '0.1.0',
|
||||||
|
}))
|
||||||
|
|
||||||
|
const mockUseBackendVersion = useBackendVersion as ReturnType<typeof vi.fn>
|
||||||
|
|
||||||
|
describe('AboutPage', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockUseBackendVersion.mockReturnValue({
|
||||||
|
data: { version: '0.1.0', commit: 'abc1234', buildTime: '2026-05-05T00:00:00Z' },
|
||||||
|
isError: false,
|
||||||
|
isLoading: false,
|
||||||
|
} as ReturnType<typeof useBackendVersion>)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders brand, description and links', () => {
|
||||||
|
render(<AboutPage />)
|
||||||
|
|
||||||
|
expect(screen.getByRole('heading', { name: 'Nex' })).toBeInTheDocument()
|
||||||
|
expect(screen.getByText('AI Gateway - 统一的大模型 API 网关')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText('GitHub')).toHaveAttribute('href', 'https://github.com/nex/gateway')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows frontend and backend versions', () => {
|
||||||
|
render(<AboutPage />)
|
||||||
|
|
||||||
|
expect(screen.getByText('前端版本')).toBeInTheDocument()
|
||||||
|
expect(screen.getAllByText('0.1.0').length).toBeGreaterThan(0)
|
||||||
|
expect(screen.getByText('abc1234')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText('2026-05-05T00:00:00Z')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows matched status', () => {
|
||||||
|
render(<AboutPage />)
|
||||||
|
|
||||||
|
expect(screen.getByText('版本一致')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows mismatched status', () => {
|
||||||
|
mockUseBackendVersion.mockReturnValue({
|
||||||
|
data: { version: '0.2.0', commit: 'abc1234', buildTime: '2026-05-05T00:00:00Z' },
|
||||||
|
isError: false,
|
||||||
|
isLoading: false,
|
||||||
|
} as ReturnType<typeof useBackendVersion>)
|
||||||
|
|
||||||
|
render(<AboutPage />)
|
||||||
|
|
||||||
|
expect(screen.getByText('版本不一致')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/用于部署诊断/)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows unknown status for dev backend version', () => {
|
||||||
|
mockUseBackendVersion.mockReturnValue({
|
||||||
|
data: { version: 'dev', commit: 'unknown', buildTime: 'unknown' },
|
||||||
|
isError: false,
|
||||||
|
isLoading: false,
|
||||||
|
} as ReturnType<typeof useBackendVersion>)
|
||||||
|
|
||||||
|
render(<AboutPage />)
|
||||||
|
|
||||||
|
expect(screen.getByText('无法判断版本')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows unavailable status on backend request failure', () => {
|
||||||
|
mockUseBackendVersion.mockReturnValue({
|
||||||
|
data: undefined,
|
||||||
|
isError: true,
|
||||||
|
isLoading: false,
|
||||||
|
} as ReturnType<typeof useBackendVersion>)
|
||||||
|
|
||||||
|
render(<AboutPage />)
|
||||||
|
|
||||||
|
expect(screen.getByText('无法获取后端版本')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/后端版本接口暂时不可用/)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
21
frontend/src/__tests__/utils/version.test.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { getVersionStatus } from '@/utils/version'
|
||||||
|
|
||||||
|
describe('getVersionStatus', () => {
|
||||||
|
it('returns matched when versions are equal', () => {
|
||||||
|
expect(getVersionStatus('1.2.3', { version: '1.2.3', commit: 'abc', buildTime: 'now' }).kind).toBe('matched')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns mismatched when release versions differ', () => {
|
||||||
|
expect(getVersionStatus('1.2.3', { version: '1.2.4', commit: 'abc', buildTime: 'now' }).kind).toBe('mismatched')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns unknown for dev or unknown versions', () => {
|
||||||
|
expect(getVersionStatus('dev', { version: '1.2.3', commit: 'abc', buildTime: 'now' }).kind).toBe('unknown')
|
||||||
|
expect(getVersionStatus('1.2.3', { version: 'unknown', commit: 'abc', buildTime: 'now' }).kind).toBe('unknown')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns unavailable on request failure', () => {
|
||||||
|
expect(getVersionStatus('1.2.3', undefined, true).kind).toBe('unavailable')
|
||||||
|
})
|
||||||
|
})
|
||||||
6
frontend/src/api/version.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import type { BackendVersion } from '@/types'
|
||||||
|
import { request } from './client'
|
||||||
|
|
||||||
|
export async function getBackendVersion(): Promise<BackendVersion> {
|
||||||
|
return request<BackendVersion>('GET', '/api/version')
|
||||||
|
}
|
||||||
@@ -1,7 +1,15 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Outlet, useLocation, useNavigate } from 'react-router'
|
import { Outlet, useLocation, useNavigate } from 'react-router'
|
||||||
import { ServerIcon, ChartLineIcon, SettingIcon, ChevronLeftIcon, ChevronRightIcon } from 'tdesign-icons-react'
|
import {
|
||||||
|
ServerIcon,
|
||||||
|
ChartLineIcon,
|
||||||
|
SettingIcon,
|
||||||
|
InfoCircleIcon,
|
||||||
|
ChevronLeftIcon,
|
||||||
|
ChevronRightIcon,
|
||||||
|
} from 'tdesign-icons-react'
|
||||||
import { Layout, Menu, Button } from 'tdesign-react'
|
import { Layout, Menu, Button } from 'tdesign-react'
|
||||||
|
import { APP_NAME } from '@/constants/app'
|
||||||
|
|
||||||
const { MenuItem } = Menu
|
const { MenuItem } = Menu
|
||||||
|
|
||||||
@@ -14,7 +22,8 @@ export function AppLayout() {
|
|||||||
if (location.pathname === '/providers') return '供应商管理'
|
if (location.pathname === '/providers') return '供应商管理'
|
||||||
if (location.pathname === '/stats') return '用量统计'
|
if (location.pathname === '/stats') return '用量统计'
|
||||||
if (location.pathname === '/settings') return '设置'
|
if (location.pathname === '/settings') return '设置'
|
||||||
return 'AI Gateway'
|
if (location.pathname === '/about') return '关于'
|
||||||
|
return APP_NAME
|
||||||
}
|
}
|
||||||
|
|
||||||
const asideWidth = collapsed ? '64px' : '232px'
|
const asideWidth = collapsed ? '64px' : '232px'
|
||||||
@@ -44,15 +53,18 @@ export function AppLayout() {
|
|||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
justifyContent: 'center',
|
justifyContent: 'center',
|
||||||
|
gap: 10,
|
||||||
fontSize: '1.25rem',
|
fontSize: '1.25rem',
|
||||||
fontWeight: 600,
|
fontWeight: 600,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{!collapsed && 'AI Gateway'}
|
<img src='/icon.png' alt={`${APP_NAME} logo`} style={{ width: 28, height: 28 }} />
|
||||||
|
{!collapsed && APP_NAME}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
operations={
|
operations={
|
||||||
<Button
|
<Button
|
||||||
|
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||||
variant='text'
|
variant='text'
|
||||||
shape='square'
|
shape='square'
|
||||||
icon={collapsed ? <ChevronRightIcon /> : <ChevronLeftIcon />}
|
icon={collapsed ? <ChevronRightIcon /> : <ChevronLeftIcon />}
|
||||||
@@ -70,6 +82,9 @@ export function AppLayout() {
|
|||||||
<MenuItem value='/settings' icon={<SettingIcon />}>
|
<MenuItem value='/settings' icon={<SettingIcon />}>
|
||||||
设置
|
设置
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
|
<MenuItem value='/about' icon={<InfoCircleIcon />}>
|
||||||
|
关于
|
||||||
|
</MenuItem>
|
||||||
</Menu>
|
</Menu>
|
||||||
</Layout.Aside>
|
</Layout.Aside>
|
||||||
<Layout style={{ marginLeft: asideWidth }}>
|
<Layout style={{ marginLeft: asideWidth }}>
|
||||||
|
|||||||
4
frontend/src/constants/app.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export const APP_NAME = 'Nex'
|
||||||
|
export const APP_DESCRIPTION = 'AI Gateway - 统一的大模型 API 网关'
|
||||||
|
export const APP_WEBSITE = 'https://github.com/nex/gateway'
|
||||||
|
export const APP_VERSION = import.meta.env.VITE_APP_VERSION || 'dev'
|
||||||
13
frontend/src/hooks/useVersion.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import * as api from '@/api/version'
|
||||||
|
|
||||||
|
export const versionKeys = {
|
||||||
|
backend: ['version', 'backend'] as const,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useBackendVersion() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: versionKeys.backend,
|
||||||
|
queryFn: api.getBackendVersion,
|
||||||
|
})
|
||||||
|
}
|
||||||
77
frontend/src/pages/About/index.tsx
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { Alert, Card, Descriptions, Link, Space, Tag } from 'tdesign-react'
|
||||||
|
import { APP_DESCRIPTION, APP_NAME, APP_VERSION, APP_WEBSITE } from '@/constants/app'
|
||||||
|
import { useBackendVersion } from '@/hooks/useVersion'
|
||||||
|
import type { VersionStatusKind } from '@/types'
|
||||||
|
import { getVersionStatus } from '@/utils/version'
|
||||||
|
|
||||||
|
const statusTheme: Record<VersionStatusKind, 'success' | 'warning' | 'default'> = {
|
||||||
|
matched: 'success',
|
||||||
|
mismatched: 'warning',
|
||||||
|
unknown: 'default',
|
||||||
|
unavailable: 'warning',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AboutPage() {
|
||||||
|
const { data: backendVersion, isError, isLoading } = useBackendVersion()
|
||||||
|
const versionStatus = getVersionStatus(APP_VERSION, backendVersion, isError)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'grid', gap: 'var(--td-comp-margin-l)' }}>
|
||||||
|
<Card bordered={false} hoverShadow>
|
||||||
|
<Space align='center' size='large'>
|
||||||
|
<img src='/icon.png' alt={`${APP_NAME} logo`} style={{ width: 56, height: 56 }} />
|
||||||
|
<div>
|
||||||
|
<h1 style={{ margin: 0, fontSize: '2rem' }}>{APP_NAME}</h1>
|
||||||
|
<p style={{ margin: '0.5rem 0 0', color: 'var(--td-text-color-secondary)', fontSize: '1rem' }}>
|
||||||
|
{APP_DESCRIPTION}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</Space>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div style={{ position: 'relative' }}>
|
||||||
|
<Card bordered={false} hoverShadow>
|
||||||
|
{(versionStatus.kind === 'mismatched' || versionStatus.kind === 'unavailable') && (
|
||||||
|
<Alert
|
||||||
|
theme='warning'
|
||||||
|
message={versionStatus.description}
|
||||||
|
style={{ marginBottom: 'var(--td-comp-margin-l)' }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Descriptions
|
||||||
|
column={2}
|
||||||
|
itemLayout='vertical'
|
||||||
|
items={[
|
||||||
|
{ label: '前端版本', content: APP_VERSION },
|
||||||
|
{ label: '后端版本', content: isLoading ? '加载中' : backendVersion?.version || 'unknown' },
|
||||||
|
{ label: '后端提交', content: isLoading ? '加载中' : backendVersion?.commit || 'unknown' },
|
||||||
|
{ label: '后端构建时间', content: isLoading ? '加载中' : backendVersion?.buildTime || 'unknown' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
<Tag
|
||||||
|
theme={statusTheme[versionStatus.kind]}
|
||||||
|
variant='light'
|
||||||
|
shape='round'
|
||||||
|
style={{ position: 'absolute', top: 'var(--td-comp-paddingLR-l)', right: 'var(--td-comp-paddingLR-l)' }}
|
||||||
|
>
|
||||||
|
{versionStatus.label}
|
||||||
|
</Tag>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card bordered={false} hoverShadow>
|
||||||
|
<Space breakLine size='large'>
|
||||||
|
<Link href={APP_WEBSITE} target='_blank' theme='primary'>
|
||||||
|
GitHub
|
||||||
|
</Link>
|
||||||
|
<Link href={APP_WEBSITE} target='_blank' theme='primary'>
|
||||||
|
文档
|
||||||
|
</Link>
|
||||||
|
<Link href={`${APP_WEBSITE}/blob/main/LICENSE`} target='_blank' theme='primary'>
|
||||||
|
License
|
||||||
|
</Link>
|
||||||
|
</Space>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -23,18 +23,16 @@ export function ModelForm({ open, model, providerId, providers, onSave, onCancel
|
|||||||
const [form] = Form.useForm()
|
const [form] = Form.useForm()
|
||||||
const isEdit = !!model
|
const isEdit = !!model
|
||||||
|
|
||||||
// 当弹窗打开或model变化时,设置表单值
|
// 当弹窗打开或 model 变化时,同步表单初始值。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open && form) {
|
if (open && form) {
|
||||||
if (model) {
|
if (model) {
|
||||||
// 编辑模式:设置现有值
|
|
||||||
form.setFieldsValue({
|
form.setFieldsValue({
|
||||||
providerId: model.providerId,
|
providerId: model.providerId,
|
||||||
modelName: model.modelName,
|
modelName: model.modelName,
|
||||||
enabled: model.enabled,
|
enabled: model.enabled,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
// 新增模式:重置表单并设置默认providerId
|
|
||||||
form.reset()
|
form.reset()
|
||||||
form.setFieldsValue({
|
form.setFieldsValue({
|
||||||
providerId,
|
providerId,
|
||||||
@@ -42,7 +40,7 @@ export function ModelForm({ open, model, providerId, providers, onSave, onCancel
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [open, model, providerId]) // 移除form依赖,避免循环
|
}, [form, open, model, providerId])
|
||||||
|
|
||||||
const handleSubmit = (context: SubmitContext) => {
|
const handleSubmit = (context: SubmitContext) => {
|
||||||
if (context.validateResult === true && form) {
|
if (context.validateResult === true && form) {
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ export function ProviderForm({ open, provider, onSave, onCancel, loading }: Prov
|
|||||||
form.setFieldsValue({ enabled: true, protocol: 'openai' })
|
form.setFieldsValue({ enabled: true, protocol: 'openai' })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [open, provider])
|
}, [form, open, provider])
|
||||||
|
|
||||||
const handleSubmit = (context: SubmitContext) => {
|
const handleSubmit = (context: SubmitContext) => {
|
||||||
if (context.validateResult === true && form) {
|
if (context.validateResult === true && form) {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { AppLayout } from '@/components/AppLayout'
|
|||||||
const ProvidersPage = lazy(() => import('@/pages/Providers'))
|
const ProvidersPage = lazy(() => import('@/pages/Providers'))
|
||||||
const StatsPage = lazy(() => import('@/pages/Stats'))
|
const StatsPage = lazy(() => import('@/pages/Stats'))
|
||||||
const SettingsPage = lazy(() => import('@/pages/Settings'))
|
const SettingsPage = lazy(() => import('@/pages/Settings'))
|
||||||
|
const AboutPage = lazy(() => import('@/pages/About'))
|
||||||
const NotFound = lazy(() => import('@/pages/NotFound'))
|
const NotFound = lazy(() => import('@/pages/NotFound'))
|
||||||
|
|
||||||
export function AppRoutes() {
|
export function AppRoutes() {
|
||||||
@@ -17,6 +18,7 @@ export function AppRoutes() {
|
|||||||
<Route path='providers' element={<ProvidersPage />} />
|
<Route path='providers' element={<ProvidersPage />} />
|
||||||
<Route path='stats' element={<StatsPage />} />
|
<Route path='stats' element={<StatsPage />} />
|
||||||
<Route path='settings' element={<SettingsPage />} />
|
<Route path='settings' element={<SettingsPage />} />
|
||||||
|
<Route path='about' element={<AboutPage />} />
|
||||||
<Route path='*' element={<NotFound />} />
|
<Route path='*' element={<NotFound />} />
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@@ -62,6 +62,20 @@ export interface StatsQueryParams {
|
|||||||
endDate?: string
|
endDate?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BackendVersion {
|
||||||
|
version: string
|
||||||
|
commit: string
|
||||||
|
buildTime: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type VersionStatusKind = 'matched' | 'mismatched' | 'unknown' | 'unavailable'
|
||||||
|
|
||||||
|
export interface VersionStatus {
|
||||||
|
kind: VersionStatusKind
|
||||||
|
label: string
|
||||||
|
description: string
|
||||||
|
}
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
status: number
|
status: number
|
||||||
code?: string
|
code?: string
|
||||||
|
|||||||
42
frontend/src/utils/version.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import type { BackendVersion, VersionStatus } from '@/types'
|
||||||
|
|
||||||
|
function isUnknownVersion(version: string | undefined): boolean {
|
||||||
|
const normalized = version?.trim().toLowerCase()
|
||||||
|
return !normalized || normalized === 'dev' || normalized === 'unknown'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getVersionStatus(
|
||||||
|
frontendVersion: string,
|
||||||
|
backendVersion?: BackendVersion,
|
||||||
|
hasError = false
|
||||||
|
): VersionStatus {
|
||||||
|
if (hasError) {
|
||||||
|
return {
|
||||||
|
kind: 'unavailable',
|
||||||
|
label: '无法获取后端版本',
|
||||||
|
description: '后端版本接口暂时不可用,当前仅展示前端版本。',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!backendVersion || isUnknownVersion(frontendVersion) || isUnknownVersion(backendVersion.version)) {
|
||||||
|
return {
|
||||||
|
kind: 'unknown',
|
||||||
|
label: '无法判断版本',
|
||||||
|
description: '当前处于开发构建或版本信息不完整,不判定为版本错误。',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (frontendVersion === backendVersion.version) {
|
||||||
|
return {
|
||||||
|
kind: 'matched',
|
||||||
|
label: '版本一致',
|
||||||
|
description: '前端和后端来自同一版本构建。',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
kind: 'mismatched',
|
||||||
|
label: '版本不一致',
|
||||||
|
description: '前后端版本不同,该状态用于部署诊断,不影响当前功能使用。',
|
||||||
|
}
|
||||||
|
}
|
||||||
1
go.work
@@ -3,4 +3,5 @@ go 1.26.2
|
|||||||
use (
|
use (
|
||||||
backend
|
backend
|
||||||
embedfs
|
embedfs
|
||||||
|
versionctl
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ cloud.google.com/go/auth v0.15.0/go.mod h1:WJDGqZ1o9E9wKIL+IwStfyn/+s59zl4Bi+1KQ
|
|||||||
cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc=
|
cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc=
|
||||||
cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg=
|
cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg=
|
||||||
cloud.google.com/go/longrunning v0.5.7/go.mod h1:8GClkudohy1Fxm3owmBGid8W0pSgodEMwEAztp38Xng=
|
cloud.google.com/go/longrunning v0.5.7/go.mod h1:8GClkudohy1Fxm3owmBGid8W0pSgodEMwEAztp38Xng=
|
||||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
|
||||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
|
||||||
github.com/ClickHouse/ch-go v0.71.0/go.mod h1:NwbNc+7jaqfY58dmdDUbG4Jl22vThgx1cYjBw0vtgXw=
|
github.com/ClickHouse/ch-go v0.71.0/go.mod h1:NwbNc+7jaqfY58dmdDUbG4Jl22vThgx1cYjBw0vtgXw=
|
||||||
github.com/ClickHouse/clickhouse-go/v2 v2.43.0/go.mod h1:o6jf7JM/zveWC/PP277BLxjHy5KjnGX/jfljhM4s34g=
|
github.com/ClickHouse/clickhouse-go/v2 v2.43.0/go.mod h1:o6jf7JM/zveWC/PP277BLxjHy5KjnGX/jfljhM4s34g=
|
||||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||||
@@ -14,6 +12,7 @@ github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmO
|
|||||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||||
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
github.com/cristalhq/acmd v0.12.0/go.mod h1:LG5oa43pE/BbxtfMoImHCQN++0Su7dzipdgBjMCBVDQ=
|
github.com/cristalhq/acmd v0.12.0/go.mod h1:LG5oa43pE/BbxtfMoImHCQN++0Su7dzipdgBjMCBVDQ=
|
||||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||||
github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE=
|
github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE=
|
||||||
@@ -26,8 +25,6 @@ github.com/go-faster/city v1.0.1/go.mod h1:jKcUJId49qdW3L1qKHH/3wPeUstCVpVSXTM6v
|
|||||||
github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo=
|
github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo=
|
||||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||||
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
|
|
||||||
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
|
||||||
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
||||||
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
|
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
|
||||||
@@ -48,6 +45,7 @@ github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwA
|
|||||||
github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
|
github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
|
||||||
github.com/jordanlewis/gcassert v0.0.0-20250430164644-389ef753e22e/go.mod h1:ZybsQk6DWyN5t7An1MuPm1gtSZ1xDaTXS9ZjIOxvQrk=
|
github.com/jordanlewis/gcassert v0.0.0-20250430164644-389ef753e22e/go.mod h1:ZybsQk6DWyN5t7An1MuPm1gtSZ1xDaTXS9ZjIOxvQrk=
|
||||||
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||||
|
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
||||||
github.com/magefile/mage v1.14.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A=
|
github.com/magefile/mage v1.14.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A=
|
||||||
@@ -66,8 +64,10 @@ github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3v
|
|||||||
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
|
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
|
||||||
github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw=
|
github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw=
|
||||||
github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||||
|
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||||
github.com/quasilyte/go-ruleguard/rules v0.0.0-20211022131956-028d6511ab71/go.mod h1:4cgAphtvu7Ftv7vOT2ZOYhC6CvBxZixcasr8qIOTA50=
|
github.com/quasilyte/go-ruleguard/rules v0.0.0-20211022131956-028d6511ab71/go.mod h1:4cgAphtvu7Ftv7vOT2ZOYhC6CvBxZixcasr8qIOTA50=
|
||||||
|
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||||
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
||||||
github.com/shirou/gopsutil/v4 v4.25.2/go.mod h1:34gBYJzyqCDT11b6bMHP0XCvWeU3J61XRT7a2EmCRTA=
|
github.com/shirou/gopsutil/v4 v4.25.2/go.mod h1:34gBYJzyqCDT11b6bMHP0XCvWeU3J61XRT7a2EmCRTA=
|
||||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-05-04
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
Nex 已经具备统一版本源:仓库根目录 `VERSION` 是权威版本,`versionctl sync` 会同步 `frontend/package.json` 和前端 `.env.*` 中的 `VITE_APP_VERSION`,Go 二进制构建通过 `-ldflags` 注入 `backend/pkg/buildinfo`。当前缺口在运行时可见性:前端只能知道自身构建版本,无法从后端获取 server/desktop 二进制版本,也无法判断前后端是否来自同一版本。
|
||||||
|
|
||||||
|
前端侧边栏当前在 `AppLayout` 中以 `AI Gateway` 作为品牌文字,折叠后 logo 区域为空,HTML title 也仍为 `AI Gateway`。About 页面只展示名称、描述和链接,缺少版本、构建信息、状态反馈和现代化信息层次。图标资源方面,前端 public 目录维护独立 SVG favicon 和未使用的 `icons.svg`,而桌面托盘和打包资源已经使用仓库 `assets/icon.png`、`assets/icon.ico`、`assets/icon.icns`。desktop 代码中的 `appName/appTooltip` 已经是 `Nex`,但现有 `desktop-app` spec 仍保留旧 tooltip 文案,需要借本次 change 同步。
|
||||||
|
|
||||||
|
本变更跨越前端页面、前端 API、后端管理接口、desktop 静态资源服务、README 和 OpenSpec,因此需要先固定实现边界,避免实现阶段出现多个版本来源或重复图标资源。
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:**
|
||||||
|
|
||||||
|
- 统一用户可见应用名称为 `Nex`,覆盖前端侧边栏、HTML title 和相关测试断言,`AI Gateway` 作为产品描述保留。
|
||||||
|
- 侧边栏展开态显示统一图标和 `Nex`,折叠态仍显示统一图标。
|
||||||
|
- 前端 favicon/public 图标复用仓库 `assets/icon.png`,清理不再使用的 SVG public 图标资源。
|
||||||
|
- About 页面展示前端版本、后端版本、后端 commit、后端 build_time 和版本匹配状态。
|
||||||
|
- 后端在 server 和 desktop 模式下都提供 `GET /api/version`。
|
||||||
|
- 明确并落地前端样式优先级:TDesign 组件 props、TDesign tokens、SCSS。
|
||||||
|
- 补充单元测试、组件测试、后端路由测试和必要的 E2E 覆盖。
|
||||||
|
- 同步更新根 README、frontend README、backend README。
|
||||||
|
|
||||||
|
**Non-Goals:**
|
||||||
|
|
||||||
|
- 不改变版本权威来源,仍以根目录 `VERSION` 为唯一版本源。
|
||||||
|
- 不新增前端或后端依赖。
|
||||||
|
- 不引入用户认证、权限控制或配置项开关。
|
||||||
|
- 不让 About 页面阻断业务功能;版本不一致仅提示,不禁止使用。
|
||||||
|
- 不重构所有已有内联样式,只处理本次触达的品牌和 About 页面相关样式。
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
### Decision: 后端版本信息复用 buildinfo 并通过 `/api/version` 暴露
|
||||||
|
|
||||||
|
后端 SHALL 新增 `GET /api/version` 管理接口,响应字段为 `version`、`commit`、`build_time`,字段值来自 `buildinfo.Version()`、`buildinfo.Commit()`、`buildinfo.BuildTime()`。
|
||||||
|
|
||||||
|
选择 `/api/version` 的原因:管理接口已经统一使用 `/api/*`,前端 API 客户端也以该路径族访问后端;`/health` 应保持存活检查语义,不混入构建元数据。选择 `buildinfo` 的原因:Makefile 已在 server 和 desktop 构建中注入版本、commit 和 buildTime,运行时读取 `VERSION` 会破坏发布产物独立性。
|
||||||
|
|
||||||
|
备选方案:扩展 `/health`。放弃原因是健康检查会被监控系统频繁调用,混入构建信息容易模糊职责,并且前端语义上需要的是管理信息而不是存活探针。
|
||||||
|
|
||||||
|
### Decision: server 和 desktop 分别注册同一个版本接口
|
||||||
|
|
||||||
|
server 和 desktop 当前拥有独立 `setupRoutes`,因此两个入口都 MUST 注册 `GET /api/version`。desktop 还需要确保该路径不会落入 SPA fallback 或协议代理路由。
|
||||||
|
|
||||||
|
备选方案:只在 server 注册。放弃原因是桌面应用使用独立路由装配和静态资源服务,用户在 desktop 模式下同样需要 About 页面展示后端版本。
|
||||||
|
|
||||||
|
### Decision: 前端版本使用 `VITE_APP_VERSION`,不运行时读取 package.json
|
||||||
|
|
||||||
|
前端 SHALL 使用 `import.meta.env.VITE_APP_VERSION` 作为自身版本,缺失时降级为 `dev` 或 `unknown` 显示。该值由版本同步工具写入 `.env.*`,符合现有构建版本注入规则。
|
||||||
|
|
||||||
|
备选方案:在前端运行时请求或打包 `package.json`。放弃原因是会产生第二个版本读取路径,并可能在 desktop 嵌入构建、生产构建和测试环境中产生不一致。
|
||||||
|
|
||||||
|
### Decision: About 页面只提示版本一致性,不阻断功能
|
||||||
|
|
||||||
|
About 页面 SHALL 根据前端版本和后端版本显示状态:一致、不一致、开发构建无法判断、后端版本获取失败。状态通过 TDesign `Tag` 和必要时的 `Alert` 展示。
|
||||||
|
|
||||||
|
判断规则:前端版本等于后端版本时为一致;任一版本为 `dev`、`unknown`、空值时为无法判断;请求失败时为后端版本获取失败;其余不相等时为不一致。
|
||||||
|
|
||||||
|
备选方案:版本不一致时阻断或弹窗提示。放弃原因是版本检查用于部署诊断,不能影响现有配置和代理能力。
|
||||||
|
|
||||||
|
### Decision: 图标资源统一到 `assets/icon.png` 并固定运行时路径
|
||||||
|
|
||||||
|
前端 public 图标 SHALL 由仓库 `assets/icon.png` 派生,实施时将根目录 `assets/icon.png` 复制为 `frontend/public/icon.png`,前端入口 SHALL 使用 `/icon.png` 作为 PNG favicon 路径。`frontend/public/favicon.svg` 不再作为 favicon 来源,`frontend/public/icons.svg` 经确认未被引用后 SHALL 删除。
|
||||||
|
|
||||||
|
Vite 会将 `frontend/public/icon.png` 输出到 dist 根目录,因此 desktop 静态服务 SHALL 显式服务 `/icon.png` 并读取嵌入 dist 中的 `icon.png`。README SHALL 标注 `frontend/public/icon.png` 来源于根目录 `assets/icon.png`,后续更新应用图标时应以根目录资源为准并同步 public 镜像。
|
||||||
|
|
||||||
|
备选方案:继续保留 SVG favicon。放弃原因是会继续存在两套应用图标来源,与用户要求的统一资源方向不一致。
|
||||||
|
|
||||||
|
### Decision: 前端样式优先级写入 README 并指导实现
|
||||||
|
|
||||||
|
实现视觉效果时,前端 SHALL 优先使用 TDesign 组件 props,例如 `Card` 的 `bordered`、`hoverShadow`、`headerBordered`,`Tag` 的 `theme`、`variant`、`shape`,`Row/Col` 的响应式 props。组件 props 不足时使用 TDesign tokens,例如 `var(--td-text-color-secondary)`、`var(--td-brand-color)`。只有 props 和 tokens 无法表达布局、响应式或品牌细节时才使用 SCSS。
|
||||||
|
|
||||||
|
备选方案:直接新增 SCSS Modules 完成全部视觉。放弃原因是项目已经在 OpenSpec 中要求优先使用 TDesign 样式体系,过多 SCSS 会增加覆盖组件内部样式的风险。
|
||||||
|
|
||||||
|
### Decision: About 页面采用信息面板布局
|
||||||
|
|
||||||
|
About 页面 SHALL 以三个独立 `Card` 垂直排列呈现:顶部品牌卡片展示图标、`Nex`、产品描述;中部版本信息卡片展示前端版本、后端版本、commit、build_time,版本状态 Tag 以绝对定位浮动在卡片右上角;下部链接卡片展示外部链接入口。
|
||||||
|
|
||||||
|
布局示意:
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ Icon Nex │
|
||||||
|
│ AI Gateway - 统一的大模型 API 网关 │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ 前端版本 后端版本 构建信息 [Tag] │
|
||||||
|
│ v0.1.0 v0.1.0 commit/time │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ GitHub / 文档 / License │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Decision: desktop-app spec 同步现有 Nex tooltip
|
||||||
|
|
||||||
|
desktop 代码已经通过 `appName = "Nex"` 和 `appTooltip = appName` 使用统一应用名称,现有 `desktop-app` spec 中 tooltip 仍写 `AI Gateway`。本次 change 已触达 `desktop-app` capability,因此 delta spec SHALL 同步修正托盘 tooltip 要求为 `Nex`,避免归档后主 spec 与当前代码继续漂移。
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- `/api/version` 在未通过 Makefile 运行的本地 Go 进程中可能返回 `dev/unknown/unknown` → About 页面将其视为开发构建,显示“无法判断”而不是错误。
|
||||||
|
- desktop 与 server 路由重复维护,可能漏注册 → 任务中明确分别添加路由测试,覆盖两个入口。
|
||||||
|
- 前端 public PNG 与根 `assets/icon.png` 可能漂移 → README 明确来源;实现阶段复制 `assets/icon.png` 到 `frontend/public/icon.png`,并通过构建验证确认 `/icon.png` 可用。
|
||||||
|
- 删除 `frontend/public/icons.svg` 可能影响隐藏引用 → 已通过全文搜索未发现引用;实现阶段删除前再次全文确认,删除后运行前端测试和构建验证。
|
||||||
|
- 样式优先级与现有 README “SCSS Modules” 表述可能冲突 → 本变更同步更新 README,以 TDesign props/tokens 优先作为新的明确规则。
|
||||||
|
- 版本不一致提示可能被误解为严重故障 → 文案应说明该状态用于部署诊断,不影响当前功能使用。
|
||||||