5.8. Go SDK
개요
이 장은 Go SDK 의 공개 이름을 모두 정리합니다. 패키지 plugin 의 함수 · 타입 · 상수를 표로 보이고, 시험에 쓰는 conformance · harness 패키지도 함께 적습니다. 설치 방법과 가장 작은 예시를 먼저 보이고, 이어서 이름을 묶음별 표로 적습니다.
패키지와 버전
| 항목 | 값 |
|---|---|
| 모듈 경로 | openmaru.io/cogentai/mindwiki/sdk/go |
| Go 버전 | 1.26 이상(go.mod 의 go 1.26.0) |
| 의존성 | 표준 라이브러리만 |
| 패키지 | plugin(SDK 본체), conformance(규약 검사), harness(가짜 위키), cmd/devharness(명령) |
설치
Go SDK 는 따로 묶은 배포 파일이 없습니다. 다음 가운데 하나로 받습니다.
모듈 프록시(GOPROXY)에서 받기. 조직의 모듈 프록시가 이 모듈을 제공하면 일반 모듈처럼 받습니다.
go get openmaru.io/cogentai/mindwiki/sdk/go
소스를 옆에 두고 replace 로 쓰 기. MindWiki 레포의 sdk/go 폴더를 복사해 두고 go.mod 에 replace 를 적습니다. 레포 안의 예시 플러그인과 시작 틀이 이 방식을 씁니다.
require openmaru.io/cogentai/mindwiki/sdk/go v0.0.0-00010101000000-000000000000
replace openmaru.io/cogentai/mindwiki/sdk/go => ../../sdk/go
인터넷이 없는 곳에서 빌드하려면 go mod vendor 로 SDK 를 vendor/ 에 넣고 함께 옮깁니다. SDK 에 외부 의존성이 없으므로 더 받을 모듈은 없습니다.
가장 작은 플러그인
시작 틀 sdk/template/go/main.go 를 줄인 것입니다. 읽기 전용 도구 echo 하나를 가집니다.
var manifest = plugin.Manifest{
ID: "template-plugin", Version: "0.1.0", Protocol: []int{plugin.Protocol},
Title: plugin.I18n{"ko": "새 플러그인", "en": "New plugin"},
Capabilities: []string{plugin.CapTools},
Tools: []plugin.Tool{{ID: "echo", ReadOnly: true, Description: "받은 글을 그대로 돌려준다.",
InputSchema: json.RawMessage(`{"type":"object","properties":{"text":{"type":"string"}}}`)}},
}
func echo(_ context.Context, _ *plugin.Request, args json.RawMessage) (plugin.ToolResult, error) {
var in struct{ Text string }
if err := json.Unmarshal(args, &in); err != nil {
return plugin.ToolResult{Text: "text 가 필요합니다", IsError: true}, nil
}
return plugin.ToolResult{Text: in.Text}, nil
}
// 지금 비밀(PLUGIN_SECRET)과, 비밀을 바꾸는 동안의 새 비밀(PLUGIN_SECRET_NEXT)
func secretsFromEnv(getenv func(string) string) map[string]string {
s := map[string]string{}
envs := map[string]string{"current": "PLUGIN_SECRET", "next": "PLUGIN_SECRET_NEXT"}
for k, env := range envs {
if v := getenv(env); v != "" {
s[k] = v
}
}
return s
}
func main() {
h := plugin.Serve(manifest, plugin.Handlers{
Tools: map[string]func(context.Context, *plugin.Request, json.RawMessage) (
plugin.ToolResult, error){"echo": echo},
}, plugin.Options{Secrets: secretsFromEnv(os.Getenv)}) // 코드 · 명령 인자에 넣지 않는다
_ = http.ListenAndServe(":9100", h)
}
공유 비밀은 환경 변수에서 읽습니다. PLUGIN_SECRET 은 지금 비밀이고, PLUGIN_SECRET_NEXT 는 시스템 관리자가 비밀을 바꾸는 동안 넣는 새 비밀입니다. 플러그인이 둘을 함께 받으면 비밀을 바꾸는 동안에도 요청이 거절되지 않습니다. 순서는 4.7. 공유 비밀 바꾸기에 있습니다.
띄우기: Serve · Options
| 이름 | 시그니처 | 설명 |
|---|---|---|
Serve | func Serve(m Manifest, h Handlers, o Options) http.Handler | 플러그인의 HTTP 처리기를 만듭니다 |
Options | 구조체 | 공유 비밀 · 경로 접두사 · 시계 · 로그 · 몸통 한도 |
Protocol | const Protocol = 1 | SDK 가 쓰는 프로토콜 버전 |
Serve 가 만든 처리기는 다음과 같이 동작합니다.
- 모든 요청(
GET /manifest포함)의 서명을 확인합니다. 서명이 틀리면 401 과 codebad_signature로 답합니다. GET /manifest에는m을 답합니다.GET /health에는Handlers.Health가 없으면{"ok": true, "version": m.Version}을 답합니다.m.Protocol이 비었으면[1]로 채웁니다.- 처리기가
*Error를 돌려주면 그 status 와 code 로 답합니다. 그 밖의 오류는 500retry로 답합니다. - 같은 경로와 같은
X-MindWiki-Delivery-Id의 요청에는 첫 답(500 미만)을 다시 줍니다. 최근 1,000건을 메모리에 둡니다. - 몸통이
MaxBody를 넘으면 413permanent로 답합니다.
Options 의 필드는 다음과 같습니다.
| 이름 | 타입 | 설명 |
|---|---|---|
Secrets | map[string]string | 위키가 서명에 쓰는 공유 비밀. 바꾸는 동안 둘 |
PathPrefix | string | 플러그인이 앞부분 경로 아래에 있을 때 끝점 앞의 경로 |
Now | func() time.Time | 시계(시험용). 기본 time.Now |
Log | *slog.Logger | 처리기 오류를 기록할 곳. 기본 slog.Default() |
MaxBody | int64 | 읽을 요청 몸통의 최대 크기. 기본 8 MiB |
Secrets 의 키 이름은 아무것이나 됩니다. 서명의 kid 가 키 이름과 같으면 SDK 는 그 비밀만 시도하고, 아니면 모든 비밀을 시도합니다.
처리기: Handlers
Handlers 는 구조체입니다. 끝점마다 처리 함수를 필드로 둡니다. 비운 끝점은 not_found 로 답합니다.
| 이름 | 타입 · 시그니처 | 끝점 |
|---|---|---|
Health | func(ctx) (HealthReport, error) | GET /health |
Verify | func(ctx, *Request) error | POST /config/verify |
Pull | func(ctx, *Request, PullInput) (PullPage, error) | POST /sync/pull |
Push | func(ctx, *Request, PushInput) (PushResult, error) | POST /sync/push |
Actions | map[string]func(ctx, *Request, ActionInput) (ActionResult, error) | POST /actions/{id} |
Tools | map[string]func(ctx, *Request, json.RawMessage) (ToolResult, error) | POST /tools/{id} |
Webhook | func(ctx, *Request, WebhookInput) (WebhookResult, error) | POST /webhook |
Notify | func(ctx, *Request, NotifyInput) (NotifyResult, error) | POST /notify |
표의 ctx 는 context.Context 입니다.
Actions·Tools의 키는 manifest 의id입니다.Verify가nil을 돌려주면 SDK 는{"ok": true}로 답합니다.Verify가 없을 때도 같습니다.Notify가 없는데/notify가 오면 SDK 는not_found가 아니라permanent로 답합니다. 위키는not_found를 「받는 사람 없음」으로 처리하기 때문입니다.Pull이Items를nil로 두면 SDK 는 빈 배열로 답합니다.Webhook의Ops도 같습니다.Push가Conflict없이 돌아오면 SDK 가ok: true를 채웁니다. 할 일과 알림의 답에도ok: true를 채웁니다.
요청: Request
| 이름 | 타입 · 시그니처 | 설명 |
|---|---|---|
Install | string | 설치 ID |
Workspace | string | 워크스페이스 ID |
Config | json.RawMessage | 설치 설정(config_schema 의 값) |
Secrets | map[string]string | 이 끝점에 실린 설치 비밀 |
Actor | Actor | 요청의 실행 주체(User · Role, 이름 · 메일 없음) |
DeliveryID | string | X-MindWiki-Delivery-Id. 다시 보내도 같은 값 |
Callback | *Callback | 위키를 다시 호출하는 클라이언트. 할 일 · 도구에만 있음 |
Attempt · MaxAttempts | int | 할 일의 X-MindWiki-Attempt(n/max). 없으면 둘 다 0 |
ConfigInto | func (r *Request) ConfigInto(v any) error | Config 를 v 에 풉니다. 비었으면 아무것도 하지 않음 |
LastAttempt | func (r *Request) LastAttempt() bool | 할 일의 마지막 시도인지 알려 줌 |
LastAttempt() 가 참일 때 retry 로 답하면, 위키는 다시 보내지 않고 할 일을 실패로 끝냅니다. 이때는 실패를 행에 적은 뒤 permanent 로 답합니다.
타입 · 함수 · 상수
끝점마다 들어오고 나가는 타입은 다음과 같습니다. 괄호 안은 이름이 다른 JSON 필드입니다.
| 타입 | 필드 | 쓰는 곳 |
|---|---|---|
HealthReport | OK(ok) · Version · Detail | Health 의 답 |
PullInput | Entity · Cursor · Limit | Pull 의 입력 |
PullPage | Items · NextCursor(next_cursor) · More · Estimate *int | Pull 의 답 |
Item | ExternalID · Updated · Title · Props · BodyMD *string · Deleted · URL | 항목 하나 |
PushInput | Entity · ExternalID · Changes · Snapshot | Push 의 입력 |
PushResult | OK · Conflict *struct{ Remote map[string]any } | Push 의 답 |
ActionInput | Input json.RawMessage · Context | 할 일의 입력 |
ActionResult | OK · Message | 할 일의 답 |
ToolResult | Text · IsError(is_error) | 도구의 답 |
WebhookInput | Headers map[string]string · BodyB64(body_b64) | 웹훅의 입력 |
WebhookResult | Ops []Op · Pull bool | 웹훅의 답 |
Op | Op · Entity · ExternalID · Title · Props · Markdown *string · Filter · Offset · Section | 웹훅 답 · 콜백의 연산 |
NotifyInput | Test · Recipient · Notification | 알림의 입력 |
NotifyResult | OK · Message | 알림의 답 |
Recipient | By · User · Email · Name · Value · Handle | 받는 사람. 이름은 오지 않음 |
Notification | ID · Kind · Mention · Title · Text · URL · Lang · CreatedAt | 알림 내용. 시험 보내기에는 ID 가 없음 |
Actor | User · Role | 요청의 실행 주체 |
ActionInput.Context에는Row·Values·Link(Entity·ExternalID) ·Fields·QueuedAt·Trigger(Type)가 있습니다.Link와Fields는 그 행이 이 설치의 짝일 때만 있습니다.Item.Props에서 키를 빼면 위키는 그 속성을 그대로 둡니다. 값의 모양은 5.4. 값 형식을 따릅니다.BodyMD가nil이면 본문을 보내지 않은 것입니다. 빈 문자열과 다릅니다.
manifest 타입은 다음과 같습니다. 각 필드의 규칙은 5.3. manifest에 있습니다.
| 타입 | 필드 | 쓰는 곳 |
|---|---|---|
Manifest | ID · Version · Protocol · Title(title_i18n) · Capabilities · ConfigSchema · SecretFields · Entities · Actions · Tools · WebhookEvents · Notify | manifest 전체 |
I18n | map[string]string. {"ko": …, "en": …} | 화면 이름 |
SecretField | Name · Title · Uses · Pattern | secret_fields |
Entity | Name · Title · Direction(pull · both) · Body · TitlePush · Fields · FullCheck *bool | entities |
Field | Name · Type · Entity · Title · ReadOnly · CreateOnly | entities[].fields |
Action | ID · Title · InputSchema | actions |
Tool | ID · Description · InputSchema · ReadOnly | tools |
NotifySpec | Recipients · HandleTitle · HandlePattern · SupportsTest | notify |
함수와 상수는 다음과 같습니다.
| 이름 | 시그니처 | 설명 |
|---|---|---|
Conflict | func Conflict(remote map[string]any) PushResult | 외부 값이 snapshot 과 다를 때의 push 답을 만듦 |
ParseAttempt | func ParseAttempt(h string) (n, maxN int) | "3/8" 을 읽음. 모양이 다르면 0, 0 |
Recipient.To | func (r Recipient) To() string | 방식에 맞는 값(이메일 · 속성 값 · 메신저 ID)을 돌려줌 |
CapSync · CapActions · CapTools · CapWebhooks · CapNotify | 문자열 상수 | capability 이름 |
RecipientEmail · RecipientAttribute · RecipientHandle | 문자열 상수 | 받는 방식 이름("email" · "attribute" · "handle") |
오류: Error
| 이름 | 시그니처 | status · code |
|---|---|---|
ErrAuth | func ErrAuth(msg string) *Error | 401 auth |
ErrRetry | func ErrRetry(msg string) *Error | 503 retry |
ErrPermanent | func ErrPermanent(msg string) *Error | 422 permanent |
ErrNotFound | func ErrNotFound(msg string) *Error | 404 not_found |
ErrUnknownOutcome | func ErrUnknownOutcome(msg string) *Error | 502 unknown_outcome |
ErrInvalidInput | func ErrInvalidInput(msg, fix string, fields ...FieldError) *Error | 400 invalid_input |
Error구조체는Status·Code·Message(JSONerror) ·Fix·Errors를 가집니다.Status가 0 이면 SDK 는 400 으로 답합니다.FieldError는Path(설정이나 입력 안의 JSON Pointer)와Message입니다.- code 상수:
CodeAuth·CodeRetry·CodePermanent·CodeInvalidInput·CodeNotFound·CodeUnknownOutcome. - 알림의 실패도 같은 함수로 돌려줍니다. 받는 사람이 없으면
ErrNotFound입니다. 다른 언어의notifyError에 해당하는 함수는 Go 에 없습니다.
return plugin.ErrInvalidInput("설정이 맞지 않습니다", "칸마다 안내를 보고 고치세요",
plugin.FieldError{Path: "/project", Message: "프로젝트 키가 필요합니다"})
code 마다 위키가 하는 일은 5.5. 오류 code에 있습니다.
콜백: Callback
| 이름 | 시그니처 | 설명 |
|---|---|---|
Callback | 구조체 URL · Token · HTTP *http.Client | Request.Callback 으로 받음 |
Ops | 아래 코드 | 연산을 50개까지 보냄 |
ReadBody | 아래 코드 | 짝인 행의 본문을 읽음(할 일만) |
OpResult | Index · Status · Code · Error · Ignored · Data | 연산 하나의 결과(ok · skipped · error) |
Body | Markdown · Rev · EditedAt · EditedBy | ReadBody 의 답 |
CallbackError | Status · Code · Detail | 콜백 요청 자체의 거절(problem+json) |
OpError | Code · Message | ReadBody 에서 위키가 거절한 연산 |
func (c *Callback) Ops(ctx context.Context, key string, ops ...Op) ([]OpResult, error)
func (c *Callback) ReadBody(ctx context.Context, key, entity, externalID,
section string) (Body, error)
key는Idempotency-Key헤더가 됩니다. 같은 키에는 첫 답이 옵니다. 키를 비우면 SDK 가 무작위 키를 만듭니다. 다시 보낼 수 있는 일에는r.DeliveryID를 바탕으로 키를 만듭니다.CallbackError.Code는bad_token·install_unavailable·rate_limited등입니다. 목록은 5.6. 콜백 API에 있습니다.OpError.Code는section_not_found·section_ambiguous·too_large·not_found·forbidden·op_not_allowed입니다.- 빈 절은 오류가 아니라 빈
Markdown입니다.
b, err := r.Callback.ReadBody(ctx, r.DeliveryID+"-body", "issue", ext, "답변")
var oe *plugin.OpError
if errors.As(err, &oe) && oe.Code == "section_not_found" {
return plugin.ActionResult{}, plugin.ErrPermanent("「답변」 절이 없습니다")
}
서명: Sign · Verify
Serve 가 서명을 확인하므로 보통은 이 함수들을 직접 쓰지 않습니다. 시험에서, 또는 다른 HTTP 프레임워크에 붙일 때 씁니다.
func Sign(secret, kid string, t time.Time, method, path string, h http.Header,
body []byte) string
func Verify(secrets map[string]string, sig string, now time.Time, method, path string,
h http.Header, body []byte) error
func SigningString(t int64, method, path string, h http.Header, body []byte) []byte
const MaxSkew = 5 * time.Minute
var ErrBadSignature, ErrStale error
| 이름 | 설명 |
|---|---|
Sign | X-MindWiki-Signature 값(t=…,kid=…,sha256=…)을 만듭니다 |
Verify | 서명을 확인합니다. kid 가 secrets 의 키와 같으면 그 비밀만, 아니면 모든 비밀을 시도합니다 |
SigningString | 서명할 문자열을 만듭니다 |
MaxSkew | 요청 시각과 플러그인 시계의 허용 차이(5분) |
ErrBadSignature · ErrStale | 서명이 다름 · 시각이 5분 넘게 다름 |
헤더 이름 상수는 HeaderSignature · HeaderProtocol · HeaderInstall · HeaderRequestID · HeaderDeliveryID · HeaderCallbackToken · HeaderCallbackURL · HeaderAttempt 입니다. 서명 문자열의 규칙은 5.2. 요청 헤더와 서명에 있습니다.
시험
Go SDK 에는 시험용 패키지 둘이 있습니다. 명령으로 쓰는 법은 5.12. devharness 와 plugin-check에 있습니다.
conformance
규약 검사입니다. 위키의 -mode plugin-check 와 devharness check 가 같은 코드를 씁니다.
| 이름 | 시그니처 | 설명 |
|---|---|---|
Run | func Run(ctx context.Context, c Config) Report | 검사를 차례로 실행합니다 |
Config | 구조체 BaseURL · Secret · InstallConfig · InstallSecrets · HTTP · Now · NotifyBy · NotifyTo | 검사할 대상과 값 |
Report | 구조체 Manifest · Checks []Check | 검사 결과 |
Report.Passed | func (r Report) Passed() bool | 실패한 검사가 없으면 참 |
Report.String | func (r Report) String() string | PASS · WARN · FAIL 줄 |
Check | 구조체 Name · OK · Warn · Detail | 검사 하나 |
시 작 틀의 시험은 다음처럼 씁니다.
srv := httptest.NewServer(handler(map[string]string{"current": "s"}))
defer srv.Close()
rep := conformance.Run(context.Background(), conformance.Config{BaseURL: srv.URL, Secret: "s"})
if !rep.Passed() {
t.Fatalf("conformance:\n%s", rep)
}
harness
devharness 의 본체입니다. Go 시험에서 가짜 위키로 쓸 수 있습니다.
| 이름 | 시그니처 | 설명 |
|---|---|---|
Harness | 구조체 URL · Secret · Config · Secrets · DeliveryID · Attempt · NotifyBy · NotifyTo · HTTP · Out · JSON · Now | 플러그인 하나를 호출하는 가짜 위키 |
Manifest · Verify · Pull · Push | 메서드 | manifest · 설정 확인 · 가져오기 · 보내기를 호출합니다 |
Action · Tool | 메서드, 답은 Call(Answer · Callbacks) | 할 일 · 도구를 호출합니다. 메모리 콜백을 열고, 받은 연산을 Call.Callbacks 로 돌려줍니다 |
Hook · Notify · Check | 메서드 | 웹훅 · 알림(NotifyCall) · 규약 검사를 호출합니다 |
ErrFailed | 구조체 Status · Body | 플러그인이 오류로 답한 호출 |
Attempt를 비우면 할 일에1/8을 보냅니다."8/8"로 두면 마지막 시도를 시험합니다. devharness 명령의-attempt가 이 값을 넣습니다.NotifyBy·NotifyTo를 채우면Check가 알림 시험 보내기를 실제로 한 건 보냅니다. 비우면Check는 그 항목을 건너뛰고 WARN 으로 표시합니다. devharness 명령의check -by·-to가 이 값을 넣습니다.- 메모리 콜백은
get_link에 짝 없음,read_rows에 빈 목록,read_body에not_found, 쓰기 연산에ok로 답합니다.