콘텐츠로 이동
AggregaAggrega
언어 선택: 한국어
이 페이지는 기계 번역되었습니다. 영어 원문 읽기.

provider 작성하기: 단계별 실습

이 페이지는 provider 게스트를 작성하는 전체 작업을, 빈 디렉터리에서 시작해 provider가 렌더링한 파일을 쓰는 빌드까지 단계별로 안내합니다. 이 페이지는 엔티티와 수명 주기를 설명하는 플러그인 개발자 가이드, 그리고 소켓을 설명하는 플러그인 계약과 함께 읽는 실습 자료입니다.

여기서 만드는 provider는 한 번에 읽을 수 있을 만큼 작으면서도 실제 작업을 수행합니다. 바로 환경 파일을 렌더링합니다. 이 대상이 첫 provider로 적합한 이유는 그 변환이 실제로 형식에 특화되어 있기 때문입니다. 환경 파일에는 고유한 키 문법과 고유한 인용 규칙이 있고, 빌드 출처 정보를 넣을 메타데이터 블록이 없습니다. 따라서 게스트는 더 큰 provider가 내리는 모든 결정을 직접 내려야 하며, 이를 가려 줄 방대한 코드도 없습니다.

이 페이지의 블록에 대하여. 출력을 보여 주는 모든 블록은 아래 단계를 나오는 순서대로 실제로 실행한 결과에서 복사한 것이며, 출력 관례를 따릅니다. 즉 블록은 완전한 것이거나, 줄이 생략된 위치를 표시한 발췌입니다. 이 문서는 복제할 수 있는 작업 공간이 아니라 직접 조립하는 실습이므로, 소스 블록은 체크아웃할 파일이 아니라 직접 만들 파일입니다.

준비물

  • 추가 도구 없이 WebAssembly로 컴파일하는 Go 툴체인.
  • 플러그인 개발자 가이드에서 소개하는 플러그인 개발 키트와, 키트가 기반으로 하는 ABI 패키지의 체크아웃. 아래 게스트의 go.mod는 둘 다를 가리킵니다.
  • aggrega 바이너리.

완성된 결과물의 형태

provider는 두 개의 산출물로 이루어집니다. .wasm 게스트와, 이를 카탈로그로 실어 나르는 Plugin 엔터티입니다. 그 밖에는 아무것도 필요하지 않습니다. 호스트 변경도, 등록도, 컴파일러 빌드도 필요 없습니다. provider를 추가한다는 것은 이 두 파일을 빌드가 볼 수 있는 곳에 추가하는 것입니다.

이 안내를 마쳤을 때의 작업 공간은 다음과 같습니다.

dotenv-walkthrough/
guest/ the Go module that compiles to the .wasm
go.mod
go.sum
main.go
catalog/ the Component and Recipe you author
component/example/compute/checkout/1.0.0/component.yaml
recipe/dotenv/checkout/1.0.0/recipe.yaml
dev-catalog/ the generated Plugin entity, with the .wasm beside it
plugin/provider/dotenv/0.1.0/plugin.yaml
plugin/provider/dotenv/0.1.0/provider--dotenv.wasm
dotenv.wasm the compiled guest
overlay.yaml the identity you supply to the entity generator
aggregate.yaml
manifest.yaml
release.yaml
.aggrega-config.yaml

1. 게스트의 자기 보고

모든 플러그인은 describe()를 내보냅니다. 호스트는 게스트를 로드할 때 이를 한 번 호출하고, 그 응답을 게스트 자신이 스스로에 대해 설명한 내용으로 읽습니다. provider의 경우 그 응답 중 네 부분이 중요합니다.

guest/main.go를 만듭니다.

// A provider guest that renders environment-file artifacts.
package main
import (
"bytes"
"fmt"
"sort"
"strings"
pdk "github.com/extism/go-pdk"
"github.com/aggrega-ai/aggrega-pdk/go/pkg/aggrega"
)
func descriptor() aggrega.PluginDescriptor {
return aggrega.PluginDescriptor{
AbiVersion: aggrega.APIVersion,
PluginType: "provider",
Description: "Render artifact bodies into environment files, quoting and escaping each value as the format requires.",
Capabilities: []string{"dotenv"},
Exports: []aggrega.PluginExport{
{Name: "render_node"},
},
Metadata: &aggrega.PluginDescriptorMeta{License: "Apache-2.0"},
}
}
//go:wasmexport describe
func describe() int32 {
out, err := aggrega.MarshalDescriptor(descriptor())
if err != nil {
pdk.SetError(err)
return 1
}
pdk.Output(out)
return 0
}

PluginType은 이 게스트가 어떤 소켓을 담당하는지 나타냅니다. Capabilities는 Recipe가 해석의 기준으로 삼는 목록입니다. spec.capability가 dotenv인 Recipe는 이 게스트로 라우팅됩니다. Exports는 호스트가 디스패치할 수 있는 진입점을 지정하며, render_node는 모든 provider가 반드시 갖추어야 하는 진입점입니다.

이 디스크립터는 초안이 대개 그렇듯 의도적으로 불완전하게 작성되었습니다. 그 점은 아래의 첫 번째 빌드에서 드러납니다.

2. 노드 렌더링

render_node는 빌드가 이 프로바이더를 통해 렌더링하는 컴포넌트마다 한 번씩 호출됩니다. 이 함수는 노드의 식별 정보, 렌더 컨텍스트, 그리고 바인딩된 Recipe가 선언한 사전 평가된 입력을 받습니다. 여기서는 호스트가 이미 읽어 템플릿으로 평가한 아티팩트 집합입니다.

게스트가 하는 일은 어떤 바이트를 출력할지 결정하는 것이 전부입니다. guest/main.go에 다음을 추가합니다:

// needsQuoting reports whether a value cannot be written bare in an
// environment file. A bare value ends at the first space, so anything
// carrying whitespace has to be quoted; the quote characters, the comment
// introducer and the expansion introducer would each be read as syntax.
func needsQuoting(v string) bool {
if v == "" {
return true
}
return strings.ContainsAny(v, " \t\n\r\"'#$\\")
}
// quote wraps a value in double quotes and escapes what the format reads as
// syntax inside them. Order matters: the backslash is escaped first, or the
// escapes introduced afterwards would be escaped a second time.
func quote(v string) string {
v = strings.ReplaceAll(v, `\`, `\\`)
v = strings.ReplaceAll(v, `"`, `\"`)
v = strings.ReplaceAll(v, "\n", `\n`)
v = strings.ReplaceAll(v, "\r", `\r`)
v = strings.ReplaceAll(v, "\t", `\t`)
return `"` + v + `"`
}
// normaliseKey maps an authored key into the environment-variable grammar:
// upper case, with the separators an author reaches for folded to
// underscores. It reports an error rather than correcting a key that still
// does not fit, because a silently-renamed variable is one the application
// never reads.
func normaliseKey(k string) (string, error) {
n := strings.ToUpper(k)
n = strings.NewReplacer("-", "_", ".", "_", "/", "_").Replace(n)
if n == "" {
return "", fmt.Errorf("empty key")
}
for i, r := range n {
switch {
case r >= 'A' && r <= 'Z', r == '_':
case r >= '0' && r <= '9' && i > 0:
default:
return "", fmt.Errorf("key %q maps to %q, which is not a valid environment-variable name", k, n)
}
}
return n, nil
}

이 코드 조각에 담긴 세 가지 결정은 프로바이더 고유의 것이며, 다른 어떤 계층도 이를 대신할 수 없습니다. 어떤 문자가 따옴표 처리를 강제하는지는 환경 파일에 관한 사실입니다. 변수 이름 문법도 마찬가지이고, 맞지 않는 키의 이름을 바꾸는 대신 거부하는 선택도 마찬가지입니다. 이름이 바뀐 변수는 애플리케이션이 찾으려 해도 찾지 못하는 변수이며, 이는 빌드가 중단되는 것보다 나쁩니다.

이제 남은 두 부분, 즉 출처 정보가 들어갈 위치와 export 자체를 살펴봅니다.

// provenanceComment renders the build-provenance key set the host computed as
// comment lines. An environment file has no metadata block, so a comment
// header is where provenance can go; the keys are emitted in sorted order so
// the bytes are identical across runs of identical input.
func provenanceComment(annotations map[string]string) []byte {
if len(annotations) == 0 {
return nil
}
keys := make([]string, 0, len(annotations))
for k := range annotations {
keys = append(keys, k)
}
sort.Strings(keys)
var out bytes.Buffer
for _, k := range keys {
fmt.Fprintf(&out, "# %s=%s\n", k, annotations[k])
}
out.WriteByte('\n')
return out.Bytes()
}
// renderBody translates one artifact body into environment-file lines. A
// blank line and a comment pass through untouched; every other line is
// KEY=value, and a line carrying no separator is a loud failure rather than a
// line the guest guesses at.
func renderBody(name string, body []byte) ([]byte, error) {
var out bytes.Buffer
for i, raw := range strings.Split(string(body), "\n") {
line := strings.TrimSpace(raw)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
k, v, found := strings.Cut(line, "=")
if !found {
return nil, fmt.Errorf("%s line %d: %q declares no value; an entry is KEY=value", name, i+1, line)
}
key, err := normaliseKey(strings.TrimSpace(k))
if err != nil {
return nil, fmt.Errorf("%s line %d: %w", name, i+1, err)
}
val := strings.TrimSpace(v)
if needsQuoting(val) {
val = quote(val)
}
fmt.Fprintf(&out, "%s=%s\n", key, val)
}
return out.Bytes(), nil
}
//go:wasmexport render_node
func render_node() int32 {
var in aggrega.RenderNodeInput
if err := in.DecodeCBOR(pdk.Input()); err != nil {
pdk.SetError(fmt.Errorf("dotenv: decode RenderNodeInput: %w", err))
return 1
}
if in.ArtifactsProjection == nil || len(in.ArtifactsProjection.Entries) == 0 {
pdk.SetError(fmt.Errorf("dotenv: node %q supplied no artifacts to render", in.Node.ID))
return 1
}
var files []aggrega.RenderedFile
for _, e := range in.ArtifactsProjection.Entries {
body, err := renderBody(e.Name, e.Content)
if err != nil {
pdk.SetError(fmt.Errorf("dotenv: %w", err))
return 1
}
files = append(files, aggrega.RenderedFile{
Path: e.Name,
Content: append(provenanceComment(e.Annotations), body...),
Format: "text",
})
}
outputBytes, err := aggrega.RenderNodeOutput{Files: files}.EncodeCBOR()
if err != nil {
pdk.SetError(fmt.Errorf("dotenv: encode RenderNodeOutput: %w", err))
return 1
}
pdk.Output(outputBytes)
return 0
}
func main() {}

페이로드는 바이너리 인코딩으로 전달되며, kit이 이를 읽고 씁니다. 호스트는 render_node에 입력을 정규 CBOR로 전달하고 응답도 같은 인코딩으로 읽으므로, 게스트는 입력 타입의 DecodeCBOR로 디코딩하고 출력 타입의 EncodeCBOR로 인코딩합니다. CBOR 라이브러리도 필요 없고, 직접 파싱하는 것도 없습니다. 파일의 Content는 게스트가 기록할 정확한 바이트로 채우는 바이트 슬라이스이며, 인코더는 이를 원시 바이트로 전달하고 호스트는 그대로 기록합니다.

호스트는 이미 평가한 콘텐츠를 게스트에 전달합니다. 각 아티팩트 항목의 Content는 작성된 본문의 템플릿 표현식이 렌더 컨텍스트에 대해 이미 해석된 결과입니다. 게스트는 템플릿을 평가하지도, 파일을 읽지도 않습니다. 이것이 컴파일러의 AOT(ahead-of-time) 경계를 온전히 유지하는 방식입니다. 게스트는 페이로드에서 바이트로 가는 순수 함수입니다.

결정성은 게스트의 책임입니다. 일반 빌드에서는 아무것도 이를 대신 검사해 주지 않습니다. 여기서는 출처 정보 키를 내보내기 전에 정렬하고 아티팩트 항목을 페이로드가 전달하는 순서대로 순회함으로써 결정성을 확보하며, 이 페이지 끝부분의 검사로 그 결과를 측정합니다.

guest/go.mod는 체크아웃한 kit을 참조합니다:

module example.com/dotenv-provider
go 1.26.0
require (
github.com/aggrega-ai/aggrega-pdk/go v0.0.0
github.com/extism/go-pdk v1.1.3
)
require github.com/aggrega-ai/aggrega-abi/go v0.0.0 // indirect
replace github.com/aggrega-ai/aggrega-pdk/go => /path/to/aggrega-pdk/go
replace github.com/aggrega-ai/aggrega-abi/go => /path/to/aggrega-abi/go

3. 게스트 빌드하기

게스트는 WebAssembly 타깃을 선택한 일반적인 Go 빌드입니다.

Terminal window
cd guest
go mod tidy
GOWORK=off GOOS=wasip1 GOARCH=wasm go build -trimpath -buildvcs=false \
-ldflags "-X github.com/aggrega-ai/aggrega-pdk/go/pkg/aggrega.Version=0.1.0 \
-X github.com/aggrega-ai/aggrega-pdk/go/pkg/aggrega.Commit=walkthru" \
-buildmode=c-shared -o ../dotenv.wasm ./

go mod tidy는 의존성의 체크섬인 go.sum을 기록하며, 빌드는 이것 없이는 실행을 거부합니다. -trimpath와 -buildvcs=false는 빌드 경로와 버전 관리 스탬프가 바이너리에 들어가지 않게 하므로, 같은 커밋의 같은 소스는 같은 바이트를 생성합니다. 두 -ldflags 값은 게스트 자체의 버전을 바이너리에 새기며, 다음 단계에서 이 값을 읽습니다.

더 진행하기 전에 export를 확인합니다.

Terminal window
aggrega inspect --plugin dotenv.wasm
Plugin .wasm: dotenv.wasm
Exports:
render_node
hostFunctions (derived from binary, not yet recorded by aggrega plugin sync): (none)

이 게스트는 호스트 함수를 하나도 import하지 않으며, 이것이 최소 권한 기본값입니다. 렌더링하는 모든 것이 페이로드로 전달되므로 파일 시스템도 네트워크도 필요하지 않습니다.

4. Plugin 엔터티 생성

엔터티의 계약 필드는 직접 작성하지 않습니다. 이 필드는 게스트에서 읽어 오므로, 엔터티가 바이너리가 하지 않는 일을 약속할 수 없습니다. 작성할 것은 작은 오버레이에 담는 식별 정보뿐입니다.

overlay.yaml:

apiVersion: aggrega.ai/v1beta1
kind: Plugin
metadata:
name: dotenv
Terminal window
aggrega plugin gen-catalog --plugin dotenv.wasm \
--overlay overlay.yaml --output-dir dev-catalog/plugin
generated dev-catalog/plugin/provider/dotenv/0.1.0/plugin.yaml

생성된 엔터티:

# Generated from the plugin by `aggrega plugin gen-catalog`. You may narrow its capability lists; edit nothing else here.
apiVersion: aggrega.ai/v1beta1
kind: Plugin
metadata:
name: dotenv
version: 0.1.0
pluginType: provider
description: Render artifact bodies into environment files, quoting and escaping each value as the format requires.
spec:
abiVersion: v1beta1
exports:
- name: render_node
provider:
capabilities:
- dotenv

여기에 없는 것에 주목하십시오. 바로 .wasm을 가리키는 포인터입니다. 플러그인의 위치는 식별 정보, 즉 pluginType/name 좌표와 구성된 레지스트리로부터 도출되므로, 작성할 위치 필드도 없고 잘못 지정할 위치 필드도 없습니다. 콘텐츠 다이제스트는 Release가 해석될 때 엔터티가 아니라 해당 Release의 lockfile에 기록됩니다.

5. 빌드가 찾을 위치에 게스트 두기

게스트를 개발하는 동안에는 가져올 게시물이 없으므로, 빌드는 카탈로그 디렉터리에서 게스트를 읽습니다. 즉, 엔터티 옆에 놓인, 소켓과 플러그인의 이름을 딴 .wasm을 읽습니다.

dev-catalog/plugin/provider/dotenv/0.1.0/plugin.yaml
dev-catalog/plugin/provider/dotenv/0.1.0/provider--dotenv.wasm
Terminal window
cp dotenv.wasm dev-catalog/plugin/provider/dotenv/0.1.0/provider--dotenv.wasm

파일 이름에 이름뿐 아니라 소켓도 담기는 이유는, 플러그인 이름만으로는 자신의 소켓 안에서만 고유하기 때문입니다. 서로 다른 소켓에 있는 dotenv라는 두 플러그인은 서로 다른 두 파일에 도달해야 합니다.

빌드된 파일을 링크하지 말고 그 위치에 복사합니다. 그 위치의 링크는 워크스페이스 안의 위치로만 따라가며, 워크스페이스 밖에 나열된 카탈로그 디렉터리의 경우에는 그 디렉터리 안의 위치로만 따라갑니다. 그보다 더 바깥을 가리키는 링크가 있으면 빌드와 풀은 그 링크를 명시하며 중단됩니다. 자세한 내용은 워크스페이스 경계에서 설명합니다.

카탈로그 디렉터리에 있는 프로바이더의 플러그인 엔터티는 고정(pin)되지 않으며, pull도 build도 그 .wasm을 가져오지 않으므로 Release가 해결될 때 파일이 그 자리에 있어야 합니다. pull은 lockfile을 쓰기 전에 확인합니다. 엔터티 옆에서도, build가 플러그인을 읽는 다른 어느 위치에서도 .wasm을 찾지 못하면, pull은 중단하고 A plugin’s .wasm is not on this machine (플러그인의 wasm 파일이 이 머신에 없음)에서 설명하는 대로 예상한 파일과 디렉터리를 알려 줍니다.

.aggrega-config.yaml에서 워크스페이스가 두 카탈로그 디렉터리를 모두 가리키도록 설정합니다:

workspace:
catalog_dirs:
- catalog
- dev-catalog
auto_pull: true

auto_pull을 사용하면 aggrega build가 프로세스 안에서 Release를 확정하므로, 첫 빌드에 별도의 확정 단계가 필요하지 않습니다.

6. provider를 대상으로 하는 문서

파일은 네 개입니다. Component는 작성자가 설정할 수 있는 항목을 선언하고, Recipe는 capability를 바인딩하고 아티팩트를 작성하며, Aggregate는 의도를 기술하고, Release는 그것을 배치합니다.

catalog/component/example/compute/checkout/1.0.0/component.yaml:

apiVersion: aggrega.ai/v1beta1
kind: Component
metadata:
name: example/compute/checkout
version: 1.0.0
description: An application whose configuration is delivered as an environment file.
labels:
component.aggrega.ai/type: server
component.aggrega.ai/category: compute
spec:
schema:
values:
service_name:
type: string
default: checkout
description: The name the application reports itself under.
log_level:
type: string
default: info
description: The application's log verbosity.
greeting:
type: string
default: hello
description: A value carrying characters the environment-file format must quote.
infra:
endpoint:
type: string
default: http://localhost:8080
description: The endpoint the operator points the application at.

catalog/recipe/dotenv/checkout/1.0.0/recipe.yaml:

apiVersion: aggrega.ai/v1beta1
kind: Recipe
metadata:
name: checkout
version: 1.0.0
description: Renders the application's configuration as an environment file.
spec:
capability: dotenv
implements: example/compute/checkout:1.0.0
artifacts:
app.env: |
service-name = {{ .values.service_name }}
log.level = {{ .values.log_level }}
greeting = {{ .values.greeting }}
endpoint = {{ .infra.endpoint }}

spec.capability: dotenv가 바인딩의 전부입니다. 이것은 플러그인이 아니라 capability를 지정합니다. 빌드는 이를 해당 capability를 선언한 provider 플러그인으로 해석합니다. 여기서처럼 그런 플러그인이 정확히 하나라면 다른 것은 필요하지 않습니다.

작성된 키는 의도적으로 환경 변수 형식이 아닙니다. service-name과 log.level은 작성자가 자연스럽게 쓸 표기이며, 이를 정규화하는 것은 provider의 일입니다.

aggregate.yaml:

apiVersion: aggrega.ai/v1beta1
kind: Aggregate
metadata:
name: aggregate
version: "1.0.0"
description: One application whose configuration is an environment file.
spec:
components:
app:
type: example/compute/checkout
values:
service_name: checkout
log_level: debug
greeting: hello world

manifest.yaml:

apiVersion: aggrega.ai/v1beta1
kind: Manifest
metadata:
name: manifest
version: "1.0.0"
description: Binds the component type to the environment-file recipe.
spec:
mappings:
components:
type:
example/compute/checkout:1.0.0: checkout:1.0.0

release.yaml:

apiVersion: aggrega.ai/v1beta1
kind: Release
metadata:
name: walkthrough
environment: production
version: "1.0.0"
spec:
aggregate: aggregate
manifest: manifest
boundaries:
infra:
directory: infra
components:
app:
infra:
endpoint: "https://checkout.example.net"

7. 첫 번째 빌드와 빌드가 거부하는 것

Terminal window
aggrega build --release release.yaml --auto-pull
warning: plugin "provider/dotenv" resolved from local with no recorded digest to check it against, so it runs unverified; it is read from beside its Plugin entity in a catalog directory on every build, and a pull records its digest only for a plugin attached at a transform role; otherwise publish the plugin and reference the published entity to have its digest recorded
[… omitted: the notice saying the Release could not be rendered to discover its external inputs, carrying the error below beneath its first line]
Pull complete: release.lock (entities=5, source_artifacts=0, external_inputs=0)
[… omitted: a line saying again that external inputs were not fully discovered]
[CATALOG_ERROR E0265] instance app
provider does not support the node's input kind (node "app"). provider "dotenv" does not support artifacts-only recipes (this provider supports: none); declare one of the supported input kinds, or target a provider that supports artifacts-only

두 줄은 서로 다른 내용을 말하므로 따로 읽어야 합니다.

경고는 개발 중에는 예상되는 것이며, 사라지지 않습니다. 이 경고는 게스트가 대조할 기록된 콘텐츠 다이제스트 없이 실행되었다는 뜻이며, 이는 방금 빌드한 게스트의 실제 상태입니다. 아무도 게스트를 게시하지 않았으므로 기록된 다이제스트가 없습니다. 경고는 또한 Release를 다시 해석해도 이것이 바뀌지 않는 이유와 — 카탈로그 디렉터리에서 엔터티 옆에 놓인 게스트는 빌드할 때마다 새로 읽히며, pull은 변환 역할에 연결된 거버넌스 플러그인에 대해서만 다이제스트를 기록하는데 이 게스트는 그런 플러그인이 아닙니다 — 무엇이 이를 바꾸는지, 즉 플러그인을 게시하고 게시된 엔터티를 참조하는 방법도 알려 줍니다. 이 경고는 빌드가 수행하지 않은 검증을 주장하지 않도록 올바르게 거절하는 것으로 읽으면 되며, 게스트가 로컬에 있는 동안에는 계속 나타날 것으로 예상하면 됩니다.

오류가 실제로 발견된 문제이며, 괄호 안의 내용이 진단입니다. provider는 발견되고 로드되었으며 무엇을 렌더링하는지 질의를 받았고, none이라고 답했습니다 — this provider supports: none. 처음에 작성한 디스크립터는 소켓, capability, 익스포트를 명시했지만, 게스트가 세 가지 Recipe 입력 종류 중 어느 것을 처리하는지는 밝히지 않았습니다. 호스트는 추측하지 않습니다. 입력 종류 게이트는 게스트가 선언한 집합을 읽고, 게스트가 한 번도 주장하지 않은 노드를 거부합니다.

이것이 처음 작성하는 provider가 실패하는 대부분의 형태입니다. 게스트 자체는 문제가 없고, 자기 보고가 불완전할 뿐입니다. describe()는 호스트가 용인하는 형식적 절차가 아닙니다. 형식에 구애받지 않는 호스트가 무엇을 어디로 보낼지 결정하는 근거의 전부입니다.

8. 렌더 동작 계약 선언하기

guest/main.go의 디스크립터에 계약을 추가합니다:

Capabilities: []string{"dotenv"},
Contract: &aggrega.ProviderContract{
InputKinds: aggrega.InputKinds{
Sourced: false,
Synthesized: false,
ArtifactsStandalone: true,
},
BoundaryAssembly: "none",
},
Exports: []aggrega.PluginExport{

ArtifactsStandalone: true는 게이트가 찾고 있던 선언입니다. 두 false 값도 선언이며, 이를 명시하는 것이 핵심입니다. 소스 트리를 벤더링하는 Recipe나 workload를 선언하는 Recipe는 이제 render_node에 도달해 그 내부 어딘가에서 실패하는 대신, 어떤 렌더도 실행되기 전에 이 provider를 명시하는 메시지와 함께 거부됩니다.

BoundaryAssembly: "none"은 각 노드의 출력이 결합할 것 없이 그것이 놓이는 위치에 기록된다는 뜻입니다. 여러 component를 하나의 문서로 합치는 provider는 대신 merge 또는 nest를 선언하고, 이를 수행하기 위해 assemble_boundary를 export합니다. 이것이 이 provider에 다음으로 추가할 자연스러운 기능이며, 플러그인 계약에 문서화되어 있습니다.

게스트를 다시 빌드하고, 엔터티를 다시 생성한 다음, 새 .wasm을 다시 그 옆에 둡니다:

Terminal window
cd guest
GOWORK=off GOOS=wasip1 GOARCH=wasm go build -trimpath -buildvcs=false \
-ldflags "-X github.com/aggrega-ai/aggrega-pdk/go/pkg/aggrega.Version=0.1.0 \
-X github.com/aggrega-ai/aggrega-pdk/go/pkg/aggrega.Commit=walkthru" \
-buildmode=c-shared -o ../dotenv.wasm ./
cd ..
aggrega plugin gen-catalog --plugin dotenv.wasm \
--overlay overlay.yaml --output-dir dev-catalog/plugin
cp dotenv.wasm dev-catalog/plugin/provider/dotenv/0.1.0/provider--dotenv.wasm

다시 생성된 엔터티는 이제 바이너리에서 읽어 온 계약을 담고 있습니다:

[… omitted: the header comments and the metadata block, unchanged from the first generation]
spec:
abiVersion: v1beta1
exports:
- name: render_node
provider:
capabilities:
- dotenv
contract:
inputKinds:
artifactsStandalone: true
boundaryAssembly: none

게스트를 다시 빌드할 때마다 엔터티를 다시 생성하는 것은 작업 루프의 일부입니다. 엔터티는 바이너리가 보고하는 내용을 다시 기술하며, 게스트가 로드될 때 두 내용이 교차 검증됩니다. 엔터티가 주장하지만 바이너리가 보고하지 않는 export나 계약 값은 불일치이며, 빌드는 그 주장을 지목하며 중단됩니다. 엔터티가 생략한 주장은 검사되지 않으므로, 이 단계처럼 바이너리에 무언가를 추가한 재빌드 뒤에 남겨진 엔터티는 여전히 로드되지만 더 이상 바이너리를 설명하지 않습니다.

9. 렌더링하는 빌드

Terminal window
aggrega build --release release.yaml --auto-pull
warning: plugin "provider/dotenv" resolved from local with no recorded digest to check it against, so it runs unverified; it is read from beside its Plugin entity in a catalog directory on every build, and a pull records its digest only for a plugin attached at a transform role; otherwise publish the plugin and reference the published entity to have its digest recorded
Pull complete: release.lock (entities=5, source_artifacts=0, external_inputs=0)
[… omitted: a line reporting total build time, which differs on every run]
Build completed: 1 file written to <workspace>/dist

마지막 줄은 출력 디렉터리를 전체 경로로 표시하며, 여기서 <workspace>는 워크스페이스 루트를 나타냅니다. 그 아래에 렌더링된 트리는 다음과 같습니다.

dist/infra/dotenv/app/app.env

그리고 provider가 작성한 파일 전체는 다음과 같습니다.

1.0.0
# aggrega.ai/boundary-path=infra
SERVICE_NAME=checkout
LOG_LEVEL=debug
GREETING="hello world"
ENDPOINT=https://checkout.example.net

guest가 내리는 모든 결정이 이 일곱 줄에 드러나 있습니다.

  • service-name과 log.level은 작성된 그대로 들어와 SERVICE_NAME과 LOG_LEVEL로 나갔습니다. 작성자는 대상 형식의 문법을 직접 쓸 필요가 없었습니다.
  • GREETING은 따옴표로 묶였고 나머지 세 개는 그렇지 않습니다. hello world에는 공백이 있어 따옴표 없이는 hello에서 끝나 버립니다. 엔드포인트에는 이 형식이 구문으로 읽는 문자가 하나도 없으므로, 따옴표로 묶으면 불필요한 잡음만 더해집니다.
  • 두 provenance 키는 주석으로 들어갔습니다. 환경 파일에는 이 키를 둘 다른 곳이 없기 때문입니다. 출력에 메타데이터 블록이 있는 provider라면 같은 키를 그곳에 둡니다. 키는 호스트가 계산했고, 배치는 guest가 선택했습니다.
  • 값은 서로 다른 두 작성자에게서 왔습니다. service_name, log_level, greeting은 Aggregate에서 온 개발자의 의도입니다. endpoint는 Release에서 온 운영자의 값입니다. guest는 이 구분을 전혀 보지 못했습니다. guest는 평가된 본문 하나를 받았을 뿐입니다.

10. 신뢰하기 전에 확인해 볼 두 가지

결정적인지 여부. 출력을 저장하고, 다시 빌드한 뒤 비교합니다:

Terminal window
cp -r dist ../capture && rm -rf dist
aggrega build --release release.yaml
diff -r ../capture dist

diff가 아무것도 출력하지 않는 것이 원하는 결과입니다. 결정성은 호스트가 아니라 게스트의 계약이며, 출력 경로 어딘가에서 Go 맵을 순회하는 게스트는 단일 빌드에서는 완벽하게 올바른 것처럼 보이지만 이 검사에서는 실패합니다.

거부가 분명하게 드러나는지 여부. Recipe의 아티팩트에서 한 줄을 망가뜨려 값을 선언하지 않도록 합니다:

artifacts:
app.env: |
service-name = {{ .values.service_name }}
this line declares no value
[… omitted: the unverified-plugin warning, and the pull's lines saying the Release could not be rendered to discover its external inputs]
[CATALOG_ERROR] instance app
rendering node "app"
caused by: wasm: plugin "provider/dotenv:0.1.0" call to render_node: dotenv: app.env line 2: "this line declares no value" declares no value; an entry is KEY=value

게스트 자체의 메시지가 그 메시지가 나온 파일 및 줄과 함께 작성자에게 그대로 전달됩니다. 이는 의도적으로 확인해 볼 가치가 있습니다. 다른 형태의 실패, 즉 파싱할 수 없는 줄을 조용히 건너뛰는 게스트는 성공하는 빌드와 변수가 누락된 배포를 만들어 내며, 출력 어디에도 그 사실이 나타나지 않기 때문입니다.

11. 다음에 추가할 것

여기서 만든 provider는 완전하지만 최소한의 구성입니다. 대략 자주 필요한 순서대로 나열하면 다음과 같습니다.

  • assemble_boundary: 여러 component의 출력을 하나의 문서로 합치며, BoundaryAssembly를 통해 선언합니다.

  • validate_node_input: 렌더링이 실행되기 전에 노드의 입력을 구조적으로 검사하여, 잘못된 입력이 렌더링 도중이 아니라 작성 경계에서 보고되도록 합니다.

  • 렌더 팩트(Render facts): 게스트가 작성한 내용 중 이 provider가 가진 환경 파일 형식에 대한 지식으로만 알 수 있는 것을 보고합니다. 여기서는 각 파일이 정의하는 변수 이름입니다. 팩트는 이름과 목록으로 이루어지며, 둘 다 이 provider 고유의 어휘이고 파일과 함께 반환됩니다. 값은 항목이 하나뿐이어도 항상 JSON 배열이어야 하며, 그렇지 않으면 빌드가 중단됩니다.

    // names lists the variables the files define, in the order they were written.
    value, err := json.Marshal(names)
    if err != nil {
    pdk.SetError(fmt.Errorf("dotenv: marshal render fact: %w", err))
    return 1
    }
    out := aggrega.RenderNodeOutput{
    Files: files,
    RenderFacts: []aggrega.RenderFact{{Name: "variable_names", Value: value}},
    }

    컴파일러는 팩트를 게스트가 나열한 순서대로 유지하고, 각 값이 목록인지만 검사하며, 그 목록을 읽는 Feature 템플릿에 전달하고, 팩트의 보고 여부와 관계없이 같은 파일을 씁니다. 각 팩트의 이름과 그 항목이 담는 내용을 provider 계약의 일부로 문서화하십시오.

  • 생략 항목(Omit entries): provider가 소스를 렌더링하게 되면 필요합니다. 소스 렌더의 입력은 SourceListing과 함께, 제외할 렌더링 단위를 지정하는 항목인 Omits를 담을 수 있습니다. 이를 준수하는 provider는 일치하는 모든 단위를 반환 결과에서 제외하고, Omitted에 항목당 하나의 개수를 보고하며, 계약에 Omits: true를 선언합니다. 이 항목은 이 provider와 같은 아티팩트 전용 렌더에는 절대 함께 오지 않으므로, 소스가 있는 입력을 렌더링한 뒤에야 만나게 됩니다. 전체 형태는 플러그인 계약의 렌더링된 단위 제외하기 에 있습니다.

  • 게시(Publishing): 로컬 dev-catalog 구성을 Release가 해석하고 검증하는 다이제스트 고정 아티팩트로 바꿉니다. 플러그인 개발자 가이드에서 게시, 풀, 빌드 단계에 걸쳐 이 수명 주기를 다룹니다.

각 소켓의 페이로드와 결과 형태는 플러그인 계약에 있습니다.