Files
zeekay add9de8fcc A module's DocType resolves with every field the module declares now
The row an install stores is the module's shape on install day, and an org
cannot change it, so a field a module added later was dropped from every
write in each org that installed earlier, with no error. GetDocType and
ListDocTypes resolve that row grown by the fields the module now declares
and it lacks, and a DocType the module added resolves from the fixture for
an org holding the module. Nothing is written on resolve; an install reads
the raw row and persists what it grows, as before. A stored always-on
DocType is an org's customization and stays whole.
2026-10-18 18:04:41 -07:00

8.7 KiB

hanzoai/framework — the DocType engine

github.com/hanzoai/framework is the metadata-driven DocType engine: native Go on SQLite, Frappe's document engine rebuilt with no Frappe/Python runtime.

It is the FOUNDATION for business apps. CMS content-types, ERPNext DocTypes, CRM records and Helpdesk tickets are all just DocTypes on this one engine, so ONE engine plus ONE generic metadata-driven renderer covers every app lane. A lane defines its DocTypes and attaches behaviour through the Go hook interface. Do not fork the engine — extend it through DocTypes and hooks.

Layering

doctype     the VALUE  — schema, coercion, naming, permission calculus. No I/O.
framework   the ENGINE — this module: store, validation-against-data, role
                         resolution, hooks, leases, operations. No transport.
host        the PLACE  — an HTTP service, a CLI, a job runner. Authenticates
                         the caller; adapts operations to its own transport.

The engine does not know what HTTP is, where its master key comes from, or how a user was authenticated. Those are the host's decisions, injected through Config and Caller. Hanzo Cloud is one host (mounting /v1/framework/*); it is not a privileged one.

Files

File Responsibility
engine.go Engine, Config, Caller, OpenDBFunc — construction and the injected seams
ops.go the OPERATION set: DocType registry, roles, modules, document CRUD + lifecycle
store.go per-org SQLite store (doctypes, documents, series, roles, locks); generic CRUD
validate.go the half of validation that reads tenant data: Link, Unique, child tables, fetch-from
permission.go role RESOLUTION, the manager gate, trust-on-first-use owner seeding
hook.go the Go lifecycle hook interface + registry
lock.go the store lease: an exclusive, TTL-bounded, cross-process interlock
ingest.go the in-process API for first-party producers (Ingest/Get/Search/…)
wire.go Doc.Wire (the redaction choke point) + ParseListQuery + BindDocument
errors.go sentinels, HookAbort, and Classify — what a failure MEANS
doctype.go re-exports the value vocabulary as aliases, so a lane needs ONE import

The two injected seams

Everything the engine used to take from its host is now one of these.

// Storage policy belongs to the host. Hanzo Cloud injects an encrypted-at-rest
// opener (KMS-held master key); a standalone app or test leaves it nil and gets
// the plain hanzoai/sqlite driver. The engine never decides encryption — it
// could only ever guess wrong.
type OpenDBFunc func(path string) (*sql.DB, error)

// Authentication belongs to the host. Org is the VALIDATED tenant, used
// verbatim and scoped onto every query, so it MUST come from a verified
// credential — never a client-supplied header. A Caller with an empty Org is
// refused before any store access.
type Caller struct {
    Org     string
    User    string
    IsAdmin bool // PLATFORM superuser, not an org admin
}

Caller is a value, not a resolver interface, deliberately: the engine needs the tenant, not the ability to go looking for one. It cannot be handed a request to inspect, so there is exactly ONE way a tenant enters the engine.

Addressing a DocType

A DocType is identified by the pair (Module, Name) — doctype.ID — because a name is unique only within its module. It renders as module.name, and that address is what a URL segment, a Link or Table target, and a stored document's doctype key all carry. doctype.ParseID reads one back; neither half may contain the dot, so the round trip is exact.

id := doctype.ID{Module: "erp", Name: "Sales Invoice"}
id.String()                       // "erp.Sales Invoice"
doctype.ParseID("erp.Item")       // doctype.ID{Module: "erp", Name: "Item"}

Operations

Every operation takes a Caller and enforces permissions itself, so authorization cannot be forgotten by a host and is not re-implemented by each one. A host's job is: decode, resolve a Caller, call, render, map the Code.

e, _ := framework.Open(framework.Config{Dir: dataDir})
defer e.Close()

invoice := doctype.ID{Module: "erp", Name: "Sales Invoice"}
doc, err := e.CreateDocument(ctx, caller, invoice, map[string]any{
    "customer": "Widgets Ltd",
})
switch framework.Classify(err) {
case framework.CodeForbidden: // 403
case framework.CodeNotFound:  // 404
case framework.CodeInvalid:   // 400
case framework.CodeConflict:  // 409
case framework.CodeRejected:  // 422 — dangling Link, or a gate hook vetoed it
}
render(doc.Wire(nil))

Classify is the ONE place that decides what a failure means. A host switches on the Code and never on a message, so hosts cannot drift.

A module's DocType resolves as the module is now

A DocType a module declares is the module's: an org cannot define or replace it (ours), so the row an install stores is only the module's shape on install day. Store.GetDocType therefore resolves that row grown by every field the module now declares and the row lacks (current, the same missing an install appends, a required field grown optional), and a DocType the module added later resolves from the fixture for any org that holds one of the module's DocTypes. ListDocTypes answers the same. Nothing is written on resolve; InstallModule reads the raw row (stored) and still persists and reports what it grows.

Why: validateDoc keeps only declared fields, so before this a release that added a field to a module wrote it nowhere in every org that had installed the module earlier, with no error. Measured in Hanzo's own CRM: crm.lead dropped program, answers, offer and the utm tags from every public form for weeks. An always-on module's stored row is the exception: no install writes one, so it is the org's customization and wins whole. Gate: TestOps_ResolveIsTheModuleAsItIsNow.

Tenant isolation (the security boundary)

Every fw_* table carries an org column and every query filters WHERE org=?, so org A's schema and data are physically invisible to org B. The org always comes from Caller.Org. There is exactly one org-derivation path.

Permissions — secure by default

  • Platform superuser (Caller.IsAdmin) is a manager everywhere.
  • Owner seeding (trust-on-first-use): the FIRST validated principal to administer an org with no role assignments becomes its System Manager, persisted ONCE via a single conditional INSERT — so "exactly one" holds under concurrency. Every later member has no privilege until granted.
  • Default-closed: a DocType is NEVER open to all. There is no "empty perms means open" path; enforcement fails closed for a role-less member.

Password fields

Hashed argon2id on write, redacted on read. Doc.Wire is the ONE choke point every document response passes through, which is why operations return a Doc (document plus its schema) rather than a bare document — handing back a bare document would let a host marshal it directly and leak the hash.

Hooks

Attach behaviour by registering a Hook from a package init():

framework.RegisterHook(invoice, framework.ActionBeforeSave,
    func(ctx context.Context, ev *framework.Event) error {
        ev.Doc.Data["total"] = computeTotal(ev.Doc.Data)  // mutation persists
        return nil
    })
Action When Abort?
ActionBeforeInsert create only, before naming/insert yes
ActionBeforeSave create AND update, before write yes (may mutate Doc.Data)
ActionAfterSave after the row is written logged, not fatal
ActionOnSubmit before docstatus 0→1 yes
ActionOnCancel before docstatus 1→2 yes
ActionOnTrash before delete yes

Hooks run outside the store transaction (the store holds a single SQLite connection; a hook touching ev.Store inside an open tx would deadlock). Gate hooks therefore run BEFORE the state change: an error aborts the operation before anything is written, and the engine wraps it as a *HookAbort so a host can tell a refusal from a fault.

Known scope boundaries

  • Schema changes (ReplaceDocType) do not retro-validate existing documents.
  • Reverse-link integrity on delete is not enforced (forward Link validation at write is).
  • after_save and multi-document hook writes are not atomic with the primary write — deliberate, to avoid the single-connection deadlock.
  • Numeric field values must arrive as float64 or string (the JSON shape). An in-process caller passing a Go int for a Float/Currency field is rejected.

Compatibility

Go module rules apply: this stays at v0.x/v1.x forever. Never v2.