parser

package
v0.8.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 12, 2026 License: MIT Imports: 9 Imported by: 1

README

parser

Package parser provides OpenFGA schema parsing for Melange.

This package wraps the official OpenFGA language parser to convert .fga schema files into Melange's internal TypeDefinition format. It isolates the OpenFGA parser dependency from other packages.

Package Responsibilities

  • Parse OpenFGA DSL files (.fga) into structured type definitions
  • Convert OpenFGA protobuf models to Melange schema types
  • Isolate external dependency on github.com/openfga/language parser

Public API

File Parsing
// ParseSchema reads an OpenFGA .fga file and returns type definitions.
func ParseSchema(path string) ([]schema.TypeDefinition, error)
String Parsing
// ParseSchemaString parses OpenFGA DSL content and returns type definitions.
func ParseSchemaString(content string) ([]schema.TypeDefinition, error)
Protobuf Conversion
// ConvertProtoModel converts an OpenFGA protobuf AuthorizationModel
// to schema TypeDefinitions. Useful for OpenFGA API integration.
func ConvertProtoModel(model *openfgav1.AuthorizationModel) []schema.TypeDefinition

Usage Examples

Parse Schema File
import "github.com/pthm/melange/pkg/parser"

types, err := parser.ParseSchema("schemas/schema.fga")
if err != nil {
    log.Fatalf("Failed to parse schema: %v", err)
}

for _, t := range types {
    fmt.Printf("Type: %s\n", t.Name)
    for _, r := range t.Relations {
        fmt.Printf("  Relation: %s\n", r.Name)
    }
}
Parse Embedded Schema
import "github.com/pthm/melange/pkg/parser"

const schemaContent = `
model
  schema 1.1

type user

type document
  relations
    define owner: [user]
    define viewer: [user] or owner
`

types, err := parser.ParseSchemaString(schemaContent)
if err != nil {
    log.Fatalf("Failed to parse schema: %v", err)
}
Parse with Go Embed
import (
    _ "embed"
    "github.com/pthm/melange/pkg/parser"
)

//go:embed schema.fga
var embeddedSchema string

func init() {
    types, err := parser.ParseSchemaString(embeddedSchema)
    if err != nil {
        panic(err)
    }
    // Use types...
}
Integration with Migration
import (
    "github.com/pthm/melange/pkg/parser"
    "github.com/pthm/melange/pkg/migrator"
)

// Parse schema
types, err := parser.ParseSchema("schemas/schema.fga")
if err != nil {
    log.Fatal(err)
}

// Migrate to database
m := migrator.NewMigrator(db, "schemas/schema.fga")
if err := m.MigrateWithTypes(ctx, types); err != nil {
    log.Fatal(err)
}
Integration with Code Generation
import (
    "github.com/pthm/melange/pkg/parser"
    "github.com/pthm/melange/pkg/clientgen"
)

// Parse schema
types, err := parser.ParseSchema("schema.fga")
if err != nil {
    log.Fatal(err)
}

// Generate type-safe client code
files, err := clientgen.Generate("go", types, nil)
if err != nil {
    log.Fatal(err)
}

for filename, content := range files {
    os.WriteFile(filename, content, 0644)
}

Error Handling

Parse errors wrap melange.ErrInvalidSchema:

import "github.com/pthm/melange/melange"

types, err := parser.ParseSchema("invalid.fga")
if err != nil {
    if errors.Is(err, melange.ErrInvalidSchema) {
        // Schema syntax error
        log.Printf("Invalid schema: %v", err)
    } else {
        // File I/O error
        log.Printf("Could not read schema: %v", err)
    }
}

Supported OpenFGA Features

The parser supports OpenFGA Schema 1.1 including:

  • Type definitions (type user, type document)
  • Direct relations ([user], [user, group])
  • Wildcard subjects ([user:*])
  • Userset references ([group#member])
  • Computed usersets / implied relations (viewer: owner)
  • Tuple-to-userset (viewer from parent)
  • Union ([user] or owner)
  • Intersection (writer and editor)
  • Exclusion (viewer but not blocked)
  • Nested expressions ((a and b) or (c but not d))

Not supported: Conditions (OpenFGA 1.2 feature)

Dependency Information

This package imports:

  • github.com/openfga/api/proto/openfga/v1 - OpenFGA protobuf types
  • github.com/openfga/language/pkg/go/transformer - OpenFGA DSL parser
  • github.com/pthm/melange/melange - Error types
  • github.com/pthm/melange/pkg/schema - Output types

The parser package is the only Melange package that imports the OpenFGA language parser, keeping other packages dependency-free.

Documentation

Overview

Package parser provides OpenFGA schema parsing for melange.

This package wraps the official OpenFGA language parser to convert .fga schema files into melange's internal TypeDefinition format. It isolates the OpenFGA parser dependency from other packages.

Basic Usage

Parse a schema file:

types, err := parser.ParseSchema("schemas/schema.fga")
if err != nil {
    log.Fatal(err)
}

Parse schema from a string:

types, err := parser.ParseSchemaString(schemaContent)

Dependency Isolation

The parser package is the only melange package that imports the OpenFGA language parser. This keeps the runtime (github.com/pthm/melange/melange) free of external dependencies.

Consumers of parsed schemas should use pkg/schema types, which have no external dependencies.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertProtoModel

func ConvertProtoModel(model *openfgav1.AuthorizationModel) []schema.TypeDefinition

ConvertProtoModel converts an OpenFGA protobuf AuthorizationModel to schema TypeDefinitions. This is useful when you have a protobuf model directly (e.g., from the OpenFGA API) rather than DSL text.

This function is used by the OpenFGA test suite adapter to convert test models without re-implementing the parsing logic.

func IsModularSchema added in v0.8.0

func IsModularSchema(path string) bool

IsModularSchema reports whether path points to an fga.mod manifest.

func ParseManifestEntries added in v0.8.0

func ParseManifestEntries(manifestContent string) (schemaVersion string, paths []string, err error)

ParseManifestEntries parses an fga.mod manifest string and returns the schema version and relative paths of all referenced module files. This enables callers to read a manifest from any source (filesystem, git, etc.) and then fetch module files individually.

func ParseModularSchema added in v0.8.0

func ParseModularSchema(manifestPath string) ([]schema.TypeDefinition, error)

ParseModularSchema parses an fga.mod manifest and all referenced module files, merging them into a unified set of type definitions.

Uses the upstream OpenFGA library for manifest parsing (TransformModFile), module merging (TransformModuleFilesToModel), and all validation including duplicate relation detection, undefined type extensions, and schema version checks.

func ParseModularSchemaFromStrings added in v0.8.0

func ParseModularSchemaFromStrings(modules map[string]string, schemaVersion string) ([]schema.TypeDefinition, error)

ParseModularSchemaFromStrings parses pre-read module contents and merges them into unified type definitions. Useful for testing and embedded schemas where module files are already in memory.

Module names are sorted for deterministic processing order.

func ParseSchema

func ParseSchema(path string) ([]schema.TypeDefinition, error)

ParseSchema reads an OpenFGA schema and returns type definitions. Accepts either a single .fga file or an fga.mod manifest for modular schemas.

For single .fga files, uses the existing single-file parser. For fga.mod manifests, reads all referenced module files and merges them into a unified model using the upstream OpenFGA library.

func ParseSchemaString

func ParseSchemaString(content string) ([]schema.TypeDefinition, error)

ParseSchemaString parses OpenFGA DSL content and returns type definitions. This is the core parser used by both file-based and string-based parsing. Wraps the OpenFGA transformer to convert protobuf models to our format.

func ReadManifestContents added in v0.8.0

func ReadManifestContents(manifestPath string) ([]byte, error)

ReadManifestContents reads an fga.mod manifest and all referenced module files, returning their concatenated contents as a single byte slice. The output is deterministic (files ordered as listed in the manifest) and suitable for content hashing in migration skip detection.

func ReadSchemaContent added in v0.8.0

func ReadSchemaContent(path string) ([]byte, error)

ReadSchemaContent reads the full content of a schema for hashing purposes. For single .fga files, returns the file bytes directly. For fga.mod manifests, returns the manifest plus all referenced module files concatenated in manifest order (deterministic).

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL