본문으로 건너뛰기

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​

이름시그니처설명
Servefunc Serve(m Manifest, h Handlers, o Options) http.Handler플러그인의 HTTP 처리기를 만듭니다
Options구조체공유 비밀 · 경로 접두사 · 시계 · 로그 · 몸통 한도
Protocolconst Protocol = 1SDK 가 쓰는 프로토콜 버전

Serve 가 만든 처리기는 다음과 같이 동작합니다.

  • 모든 요청(GET /manifest 포함)의 서명을 확인합니다. 서명이 틀리면 401 과 code bad_signature 로 답합니다.
  • GET /manifest 에는 m 을 답합니다. GET /health 에는 Handlers.Health 가 없으면 {"ok": true, "version": m.Version} 을 답합니다.
  • m.Protocol 이 비었으면 [1] 로 채웁니다.
  • 처리기가 *Error 를 돌려주면 그 status 와 code 로 답합니다. 그 밖의 오류는 500 retry 로 답합니다.
  • 같은 경로와 같은 X-MindWiki-Delivery-Id 의 요청에는 첫 답(500 미만)을 다시 줍니다. 최근 1,000건을 메모리에 둡니다.
  • 몸통이 MaxBody 를 넘으면 413 permanent 로 답합니다.

Options 의 필드는 다음과 같습니다.

이름타입설명
Secretsmap[string]string위키가 서명에 쓰는 공유 비밀. 바꾸는 동안 둘
PathPrefixstring플러그인이 앞부분 경로 아래에 있을 때 끝점 앞의 경로
Nowfunc() time.Time시계(시험용). 기본 time.Now
Log*slog.Logger처리기 오류를 기록할 곳. 기본 slog.Default()
MaxBodyint64읽을 요청 몸통의 최대 크기. 기본 8 MiB

Secrets 의 키 이름은 아무것이나 됩니다. 서명의 kid 가 키 이름과 같으면 SDK 는 그 비밀만 시도하고, 아니면 모든 비밀을 시도합니다.

처리기: Handlers​

Handlers 는 구조체입니다. 끝점마다 처리 함수를 필드로 둡니다. 비운 끝점은 not_found 로 답합니다.

이름타입 · 시그니처끝점
Healthfunc(ctx) (HealthReport, error)GET /health
Verifyfunc(ctx, *Request) errorPOST /config/verify
Pullfunc(ctx, *Request, PullInput) (PullPage, error)POST /sync/pull
Pushfunc(ctx, *Request, PushInput) (PushResult, error)POST /sync/push
Actionsmap[string]func(ctx, *Request, ActionInput) (ActionResult, error)POST /actions/{id}
Toolsmap[string]func(ctx, *Request, json.RawMessage) (ToolResult, error)POST /tools/{id}
Webhookfunc(ctx, *Request, WebhookInput) (WebhookResult, error)POST /webhook
Notifyfunc(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​

이름타입 · 시그니처설명
Installstring설치 ID
Workspacestring워크스페이스 ID
Configjson.RawMessage설치 설정(config_schema 의 값)
Secretsmap[string]string이 끝점에 실린 설치 비밀
ActorActor요청의 실행 주체(User · Role, 이름 · 메일 없음)
DeliveryIDstringX-MindWiki-Delivery-Id. 다시 보내도 같은 값
Callback*Callback위키를 다시 호출하는 클라이언트. 할 일 · 도구에만 있음
Attempt · MaxAttemptsint할 일의 X-MindWiki-Attempt(n/max). 없으면 둘 다 0
ConfigIntofunc (r *Request) ConfigInto(v any) errorConfig 를 v 에 풉니다. 비었으면 아무것도 하지 않음
LastAttemptfunc (r *Request) LastAttempt() bool할 일의 마지막 시도인지 알려 줌

LastAttempt() 가 참일 때 retry 로 답하면, 위키는 다시 보내지 않고 할 일을 실패로 끝냅니다. 이때는 실패를 행에 적은 뒤 permanent 로 답합니다.

타입 · 함수 · 상수​

끝점마다 들어오고 나가는 타입은 다음과 같습니다. 괄호 안은 이름이 다른 JSON 필드입니다.

타입필드쓰는 곳
HealthReportOK(ok) · Version · DetailHealth 의 답
PullInputEntity · Cursor · LimitPull 의 입력
PullPageItems · NextCursor(next_cursor) · More · Estimate *intPull 의 답
ItemExternalID · Updated · Title · Props · BodyMD *string · Deleted · URL항목 하나
PushInputEntity · ExternalID · Changes · SnapshotPush 의 입력
PushResultOK · Conflict *struct{ Remote map[string]any }Push 의 답
ActionInputInput json.RawMessage · Context할 일의 입력
ActionResultOK · Message할 일의 답
ToolResultText · IsError(is_error)도구의 답
WebhookInputHeaders map[string]string · BodyB64(body_b64)웹훅의 입력
WebhookResultOps []Op · Pull bool웹훅의 답
OpOp · Entity · ExternalID · Title · Props · Markdown *string · Filter · Offset · Section웹훅 답 · 콜백의 연산
NotifyInputTest · Recipient · Notification알림의 입력
NotifyResultOK · Message알림의 답
RecipientBy · User · Email · Name · Value · Handle받는 사람. 이름은 오지 않음
NotificationID · Kind · Mention · Title · Text · URL · Lang · CreatedAt알림 내용. 시험 보내기에는 ID 가 없음
ActorUser · Role요청의 실행 주체
  • ActionInput.Context 에는 Row · Values · Link(Entity · ExternalID) · Fields · QueuedAt · Trigger(Type)가 있습니다. Link 와 Fields 는 그 행이 이 설치의 짝일 때만 있습니다.
  • Item.Props 에서 키를 빼면 위키는 그 속성을 그대로 둡니다. 값의 모양은 5.4. 값 형식을 따릅니다.
  • BodyMD 가 nil 이면 본문을 보내지 않은 것입니다. 빈 문자열과 다릅니다.

manifest 타입은 다음과 같습니다. 각 필드의 규칙은 5.3. manifest에 있습니다.

타입필드쓰는 곳
ManifestID · Version · Protocol · Title(title_i18n) · Capabilities · ConfigSchema · SecretFields · Entities · Actions · Tools · WebhookEvents · Notifymanifest 전체
I18nmap[string]string. {"ko": …, "en": …}화면 이름
SecretFieldName · Title · Uses · Patternsecret_fields
EntityName · Title · Direction(pull · both) · Body · TitlePush · Fields · FullCheck *boolentities
FieldName · Type · Entity · Title · ReadOnly · CreateOnlyentities[].fields
ActionID · Title · InputSchemaactions
ToolID · Description · InputSchema · ReadOnlytools
NotifySpecRecipients · HandleTitle · HandlePattern · SupportsTestnotify

함수와 상수는 다음과 같습니다.

이름시그니처설명
Conflictfunc Conflict(remote map[string]any) PushResult외부 값이 snapshot 과 다를 때의 push 답을 만듦
ParseAttemptfunc ParseAttempt(h string) (n, maxN int)"3/8" 을 읽음. 모양이 다르면 0, 0
Recipient.Tofunc (r Recipient) To() string방식에 맞는 값(이메일 · 속성 값 · 메신저 ID)을 돌려줌
CapSync · CapActions · CapTools · CapWebhooks · CapNotify문자열 상수capability 이름
RecipientEmail · RecipientAttribute · RecipientHandle문자열 상수받는 방식 이름("email" · "attribute" · "handle")

오류: Error​

이름시그니처status · code
ErrAuthfunc ErrAuth(msg string) *Error401 auth
ErrRetryfunc ErrRetry(msg string) *Error503 retry
ErrPermanentfunc ErrPermanent(msg string) *Error422 permanent
ErrNotFoundfunc ErrNotFound(msg string) *Error404 not_found
ErrUnknownOutcomefunc ErrUnknownOutcome(msg string) *Error502 unknown_outcome
ErrInvalidInputfunc ErrInvalidInput(msg, fix string, fields ...FieldError) *Error400 invalid_input
  • Error 구조체는 Status · Code · Message(JSON error) · 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.ClientRequest.Callback 으로 받음
Ops아래 코드연산을 50개까지 보냄
ReadBody아래 코드짝인 행의 본문을 읽음(할 일만)
OpResultIndex · Status · Code · Error · Ignored · Data연산 하나의 결과(ok · skipped · error)
BodyMarkdown · Rev · EditedAt · EditedByReadBody 의 답
CallbackErrorStatus · Code · Detail콜백 요청 자체의 거절(problem+json)
OpErrorCode · MessageReadBody 에서 위키가 거절한 연산
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
이름설명
SignX-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 가 같은 코드를 씁니다.

이름시그니처설명
Runfunc Run(ctx context.Context, c Config) Report검사를 차례로 실행합니다
Config구조체 BaseURL · Secret · InstallConfig · InstallSecrets · HTTP · Now · NotifyBy · NotifyTo검사할 대상과 값
Report구조체 Manifest · Checks []Check검사 결과
Report.Passedfunc (r Report) Passed() bool실패한 검사가 없으면 참
Report.Stringfunc (r Report) String() stringPASS · 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 로 답합니다.

관련 문서​