SDK generation plugin

The sdks plugin generates a language-specific SDK from the database's exported definitions. This release supports Go.

Configuration

Enable the plugin and set the output directory:

TRON139 B
Offset (hex)Bytes (hex)Meaning
0054 52 4F 4Emagic TRON
044C 70617468txt "path"
096C 6170702E6462txt "app.db"
100F 0A 04000000 0900 0000map leaf, size 10: @4 → @9
1A9C 6469726563746F 7279txt "directory"
245C 2E2F73646Btxt "./sdk"
2A0F 0A 1A000000 2400 0000map leaf, size 10: @1A → @24
342C 676Ftxt "go"
370F 0A 34000000 2A00 0000map leaf, size 10: @34 → @2A
418C 64617461626173 65txt "database"
4A0F 0A 41000000 1000 0000map leaf, size 10: @41 → @10
544C 73646B73txt "sdks"
590F 0A 54000000 3700 0000map leaf, size 10: @54 → @37
6307 0E 00500000 4A00 0000 59000000map branch, size 14, depth 0 (root), slots 12, 14: @4A → @59
717C 706C7567696E73txt "plugins"
790F 0A 71000000 6300 0000map leaf, size 10: @71 → @63
SettingRequirementDescription
sdks.goOptionalEnables the Go generator.
sdks.go.directoryRequired when go is enabled; nonempty stringDirectory for generated Go source; relative paths are resolved from the process working directory.

With no language configured, sdks does not generate files. There is no default output directory. Select stdlib and database separately if the definitions or application need them.

An enabled SDK is generated when the database opens and refreshed after definitions are updated. The output directory contains sdk.go and schemas/schemas.go.

Go configuration

The Go binding can express the same configuration with Go structs:

go301 B
config := stardust.Config{
    Plugins: &stardust.Plugins{
        Stdlib:   true,
        Database: &stardust.DatabaseSettings{Path: "app.db"},
        SDKs: &stardust.SDKSettings{
            Go: &stardust.GoSDKSettings{Directory: "./sdk"},
        },
    },
}
db, err := stardust.OpenConfig(config)

SDK generation

The configured SDK directory contains these generated files:

  • sdk.go contains namespace structs, exported values and methods for exported functions.
  • schemas/schemas.go contains types for exported schemas.

For example, an exported function add in namespace spice/models produces this database method:

go41 B
result, err := db.SpiceModels.Add(20, 22)

Fixed arities with simple contracts use Go types. Definitions without a specific type use sdk.Value, with a closed set of Stardust value variants. Schema shapes produce Go structs, and other schemas produce Go aliases. The generated structs contain the schema's declared fields. Literal string, integer, float, boolean, bytes, list, and map exports become fields on their namespace struct. Other exported values, including computed values, use sdk.Value.

The generated methods cover exported defquery, defmutation, and defn forms, and exported def forms whose value is an inline fn. A query with a simple named find list or a field projection also generates a row struct. A schema clause or result contract can give the fields their Go types. Generated schema types cover exported defschema forms. Function names can use ASCII letters, digits, and _ - ? ! * + < > = ..

Mutation methods return a fixed result with the transaction and created IDs. Mutations that create entities for query rows return slices of IDs. For a checked mutation, a parameter assigned directly to a schema-constrained field uses that field's Go type.

Using the generated Go SDK

Import the generated SDK from your Go module. With the spice/models/add function saved in app.db, open the database and call its generated method:

go290 B
db, err := sdk.Open(sdk.Config{Plugins: &sdk.Plugins{
    Stdlib:   true,
    Database: &sdk.DatabaseSettings{Path: "app.db"},
}})
if err != nil {
    log.Fatal(err)
}
defer db.Close()

result, err := db.SpiceModels.Add(20, 22)
if err != nil {
    log.Fatal(err)
}
fmt.Println(result) // 42

Query and mutation methods

Export defquery and defmutation declarations to generate Go methods. For example, save these forms in spice/models:

TRON781 B
Offset (hex)Bytes (hex)Meaning
00054 52 4F 4Emagic TRON
0046C 236C6F63616Ctxt "#local"
00B7C 76657273696F6Etxt "version"
0130F 0A 04000000 0B00 0000map leaf, size 10: @4 → @B
01D3C 646566txt "def"
02102 03000000000000 00i64 3
02A0E 15 00 0700 030000 00 1D000000 130000 00 21000000array leaf, size 21, shift 0, bitmap 0007, count 3 (root): @1D → @13 → @21
03F7C 23696E766F6B65txt "#invoke"
0470F 0A 3F000000 2A00 0000map leaf, size 10: @3F → @2A
0516C 236C6F63616Ctxt "#local"
0586C 637265617465txt "create"
05F0F 0A 51000000 5800 0000map leaf, size 10: @51 → @58
0696C 236C6F63616Ctxt "#local"
0704C 6E616D65txt "name"
0750F 0A 69000000 7000 0000map leaf, size 10: @69 → @70
07F0E 0D 00 0100 010000 00 75000000array leaf, size 13, shift 0, bitmap 0001, count 1 (root): @75
08C6C 236C6F63616Ctxt "#local"
0937C 737472696E673Ftxt "string?"
09B0F 0A 8C000000 9300 0000map leaf, size 10: @8C → @93
0A54C 6E616D65txt "name"
0AA0F 0A A5000000 9B00 0000map leaf, size 10: @A5 → @9B
0B46C 236C6F63616Ctxt "#local"
0BB4C 6E616D65txt "name"
0C00F 0A B4000000 BB00 0000map leaf, size 10: @B4 → @BB
0CA4C 6E616D65txt "name"
0CF0F 0A CA000000 C000 0000map leaf, size 10: @CA → @C0
0D95C 5F6974656Dtxt "_item"
0DF0F 0A D9000000 CF00 0000map leaf, size 10: @D9 → @CF
0E95C 7061746368txt "patch"
0EF0F 0A E9000000 DF00 0000map leaf, size 10: @E9 → @DF
0F96C 736368656D61txt "schema"
1000F 0A F9000000 AA00 0000map leaf, size 10: @F9 → @AA
Show all 82 nodes
Offset (hex)Bytes (hex)Meaning
10A07 0E 01040000 EF00 0000 00010000map branch, size 14, depth 1, slots 0, 10: @EF → @100
11807 0A 80000000 0A01 0000map branch, size 10, depth 0 (root), slots 7: @10A
122BC 6465666D757461 74696F6Etxt "defmutation"
12E0E 19 00 0F00 040000 00 22010000 5F0000 00 7F000000 180100 00array leaf, size 25, shift 0, bitmap 000F, count 4 (root): @122 → @5F → @7F → @118
1477C 23696E766F6B65txt "#invoke"
14F0F 0A 47010000 2E01 0000map leaf, size 10: @147 → @12E
1596C 236C6F63616Ctxt "#local"
1606C 70656F706C65txt "people"
1670F 0A 59010000 6001 0000map leaf, size 10: @159 → @160
1710E 09 00 0000 000000 00array leaf, size 9, shift 0, bitmap 0000, count 0 (root)
17A6C 236C6F63616Ctxt "#local"
1816C 736368656D61txt "schema"
1880F 0A 7A010000 8101 0000map leaf, size 10: @17A → @181
1926C 236C6F63616Ctxt "#local"
1997C 737472696E673Ftxt "string?"
1A10F 0A 92010000 9901 0000map leaf, size 10: @192 → @199
1AB4C 6E616D65txt "name"
1B00F 0A AB010000 A101 0000map leaf, size 10: @1AB → @1A1
1BA6C 236C6F63616Ctxt "#local"
1C12C 3F65txt "?e"
1C40F 0A BA010000 C101 0000map leaf, size 10: @1BA → @1C1
1CE0E 15 00 0700 030000 00 88010000 B00100 00 C4010000array leaf, size 21, shift 0, bitmap 0007, count 3 (root): @188 → @1B0 → @1C4
1E30E 0D 00 0100 010000 00 CE010000array leaf, size 13, shift 0, bitmap 0001, count 1 (root): @1CE
1F04C 6E616D65txt "name"
1F509bit true
1F60F 0A F0010000 F501 0000map leaf, size 10: @1F0 → @1F5
2002C 3F65txt "?e"
2030F 0A 00020000 F601 0000map leaf, size 10: @200 → @1F6
20D5C 7768657265txt "where"
2130F 0A 0D020000 E301 0000map leaf, size 10: @20D → @1E3
21D7C 70726F6A656374txt "project"
2250F 0A 1D020000 0302 0000map leaf, size 10: @21D → @203
22F07 0E 02040000 1302 0000 25020000map branch, size 14, depth 0 (root), slots 1, 10: @213 → @225
23D8C 64656671756572 79txt "defquery"
2460E 19 00 0F00 040000 00 3D020000 670100 00 71010000 2F0200 00array leaf, size 25, shift 0, bitmap 000F, count 4 (root): @23D → @167 → @171 → @22F
25F7C 23696E766F6B65txt "#invoke"
2670F 0A 5F020000 4602 0000map leaf, size 10: @25F → @246
2716C 236C6F63616Ctxt "#local"
2787C 76657273696F6Etxt "version"
2800F 0A 71020000 7802 0000map leaf, size 10: @271 → @278
28A6C 236C6F63616Ctxt "#local"
2916C 637265617465txt "create"
2980F 0A 8A020000 9102 0000map leaf, size 10: @28A → @291
2A26C 236C6F63616Ctxt "#local"
2A96C 70656F706C65txt "people"
2B00F 0A A2020000 A902 0000map leaf, size 10: @2A2 → @2A9
2BA6C 6578706F7274txt "export"
2C10E 19 00 0F00 040000 00 BA020000 800200 00 98020000 B00200 00array leaf, size 25, shift 0, bitmap 000F, count 4 (root): @2BA → @280 → @298 → @2B0
2DA7C 23696E766F6B65txt "#invoke"
2E20F 0A DA020000 C102 0000map leaf, size 10: @2DA → @2C1
2EC0E 19 00 0F00 040000 00 47000000 4F0100 00 67020000 E20200 00array leaf, size 25, shift 0, bitmap 000F, count 4 (root): @47 → @14F → @267 → @2E2
Offset (hex)Bytes (hex)Meaning

The generated namespace exposes the literal scalar export and both methods:

go223 B
fmt.Println(db.SpiceModels.Version) // 3
_, err := db.SpiceModels.Create("Ada")
if err != nil {
    log.Fatal(err)
}
people, err := db.SpiceModels.People()
if err != nil {
    log.Fatal(err)
}
fmt.Println(people) // [{Ada}]

Subscribing to query results

Each exported defquery also generates a SubscribeTo method with the same parameters. It returns a *stardust.Subscription of the query's row type. Events returns an iterator over the results, and Next waits for one result. The first result is the current result. After each commit that changes a field that the query reads, or the namespace that defines the query, the subscription delivers a new result. Each result is complete. When a newer result arrives before Next takes the previous one, the newer result replaces it:

go464 B
sub, err := db.SpiceModels.SubscribeToPeople()
if err != nil {
    log.Fatal(err)
}
defer sub.Close()

ctx, cancel := context.WithCancel(context.Background())
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
    defer wg.Done()
    for event, err := range sub.Events(ctx) {
        if err != nil {
            return // context.Canceled after cancel
        }
        fmt.Println(event.Result) // [{Ada}]
    }
}()

// ... write to the database ...

cancel()
wg.Wait()

An error from Next is the last step of Events. Close cancels the subscription. After Close, Next returns stardust.ErrSubscriptionClosed. When the database closes, Next returns stardust.ErrClosed. When ctx ends, Next returns its error and the subscription continues. Without a generated SDK, use stardust.Subscribe[T](db, "spice/models", "people").

Reading reactor stats

A saved defreactor runs inside each write that changes a field it reads or writes. The generated SDK has no method for a reactor. Read the facts that it writes with a query. db.Reactors() returns a []stardust.ReactorStats with each saved reactor and its work since the database opened:

go217 B
stats, err := db.Reactors()
if err != nil {
    log.Fatal(err)
}
for _, reactor := range stats {
    fmt.Printf("%s/%s: %d runs, %d changes\n",
        reactor.Namespace, reactor.Name, reactor.Runs, reactor.Changes)
}

LastTx is the last transaction that the reactor changed. Failures counts the writes that it caused to fail, and LastFailure holds the last message. LastTx and LastFailure are nil until they have a value.

Updating definitions from a directory

On an open *stardust.Database, save the DUST files in a directory as namespaces. For example, definitions/people/models.dust supplies the forms for people/models:

go200 B
response, err := db.UpdateDefinitionsFromDir("./definitions")
if err != nil {
    log.Fatal(err)
}
for _, namespace := range response.Namespaces {
    fmt.Println(namespace.Path, namespace.Revision)
}

The files are saved together in one transaction. Removing a file does not delete its previously saved namespace. If the SDK plugin is enabled, it regenerates the SDK after the transaction commits. A *stardust.DefinitionsError with Outcome set to "committed" means the definitions were saved but a plugin could not complete its update.

Using the released Go binding

The release archive includes the stardust Go module in abi/bindings/go and the native libraries in abi/lib. In your application module, point Go at the extracted release. For example, on Linux x86-64, set STARDUST_RELEASE to the absolute path of the extracted archive, then run:

sh94 B
go mod edit -require=stardust@v0.0.0 \
  -replace=stardust="$STARDUST_RELEASE/abi/bindings/go"

The released binding links to the native library in abi/lib on Linux x86-64 and ARM64. The generated SDK imports this binding as stardust.

Using the Go ABI binding

Import the released binding to send requests directly:

go17 B
import "stardust"

Decode creates a Document. Submit accepts request Documents and returns their UUIDs. Poll returns response Documents. Close each document when you no longer need it. A poll wait of -1 waits for a response:

go1.1 kB
config, err := stardust.Decode(`{workers 1 plugins <stdlib database>}`)
if err != nil {
    log.Fatal(err)
}
defer config.Close()
db, err := stardust.Open(config)
if err != nil {
    log.Fatal(err)
}
defer db.Close()

request, err := stardust.Decode(`{method "eval" params {code (+ 20 22)}}`)
if err != nil {
    log.Fatal(err)
}
defer request.Close()
ids, err := db.Submit(request)
if err != nil {
    log.Fatal(err)
}
responses, err := db.Poll(-1)
if err != nil {
    for index := range responses {
        if closeErr := responses[index].Close(); closeErr != nil {
            log.Print(closeErr)
        }
    }
    log.Fatal(err)
}
fmt.Println(ids[0]) // Match this request with the response causation-id.
for index := range responses {
    response := responses[index]
    text, err := response.Encode()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Print(text) // The response has result 42 and UUID message fields.
    message, err := response.Message()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(message.CausationID == ids[0])
    if err := response.Close(); err != nil {
        log.Fatal(err)
    }
}

For a saved function, the binding also offers Call and typed CallAs. Use the same handle for function calls:

go72 B
result, err := stardust.CallAs[int64](db, "spice/models", "add", 20, 22)

Generated calls match their responses by causation ID. Poll raw responses concurrently with large submissions so the bounded queues can make progress.