Documentation
¶
Overview ¶
Package fabric provides helpers for interacting with Microsoft Fabric notebook items: parsing their definitions and triggering RunNotebook jobs.
Index ¶
- Constants
- func ClearCachedTokens(profile string) error
- func GetAccessToken(profile string) (string, error)
- func GetNotebookIpynb(token, workspaceID, itemID string) ([]byte, error)
- func GetWorkspaceID(token, name string) (string, error)
- func QueryRefreshableTables(token, workspaceID, datasetID string) ([]string, error)
- func RebindReport(token, workspaceID, reportID, datasetID string) error
- func RunNotebook(token, workspaceID, itemID string, inputs []JobInput, ...) (string, error)
- func SetProfile(p string)
- func SetUserAgent(v string)
- func TriggerRefresh(token, workspaceID, datasetID string, tables []string) (string, error)
- func UpdateItemDefinition(token, workspaceID, itemID string, def *Definition) error
- type Dataset
- type DefaultLakehouse
- type Definition
- type DefinitionPart
- type Item
- func CreateItem(token, workspaceID, displayName, itemType string, def *Definition) (Item, error)
- func FindNotebookByName(token, workspaceID, name string) (Item, error)
- func ListItems(token, workspaceID string) ([]Item, error)
- func ListItemsByType(token, workspaceID, itemType string) ([]Item, error)
- func ListNotebooks(token, workspaceID string) ([]Item, error)
- type JobInput
- type JobInstanceStatus
- type LakehouseBinding
- type Parameter
- type RefreshMessage
- type RefreshStatus
- type Workspace
Constants ¶
const ( JobStatusCompleted = "Completed" JobStatusFailed = "Failed" JobStatusCancelled = "Cancelled" JobStatusDeduped = "Deduped" )
Job instance status values returned by Fabric. The first four are terminal; anything else means "still running".
const ( TypeString = "string" TypeBool = "bool" TypeInt = "int" TypeFloat = "float" )
Fabric RunNotebook parameter types. These match the lowercase Python-style names that fabric-cli uses (see fab_types.py in microsoft/fabric-cli) and that the user's original API example demonstrated.
Variables ¶
This section is empty.
Functions ¶
func ClearCachedTokens ¶
ClearCachedTokens wipes all stored tokens for a profile. It returns a non-nil error if any keyring delete fails for a reason other than the entry being absent — keyring.ErrNotFound is the normal "nothing to wipe" case (the "default" profile, a customer that never authenticated) and is treated as success. Surfacing real failures lets logout report honestly instead of printing a false "cleared" when the keyring is locked or otherwise refuses the delete, leaving a long-lived refresh token behind.
func GetAccessToken ¶
GetAccessToken returns a Fabric access token for the given profile name, using cached/refreshed tokens when possible, falling back to browser auth. Pass "default" if you don't need multi-tenant support yet.
As a side effect, the profile is remembered package-wide via SetProfile so the HTTP wrappers' 401-retry path can mint a fresh token mid-flow without every caller threading the profile through pollers / interfaces.
func GetNotebookIpynb ¶
GetNotebookIpynb returns the raw .ipynb bytes of a notebook item. Thin wrapper over GetItemDefinition that extracts the .ipynb part.
func GetWorkspaceID ¶
GetWorkspaceID resolves a workspace by displayName. Thin wrapper around ListWorkspaces because Fabric Core doesn't support $filter on workspaces.
func QueryRefreshableTables ¶
QueryRefreshableTables returns the names of tables in a semantic model that the Enhanced Refresh API can actually process. We fetch the model's TMDL definition via Fabric getDefinition, then keep only tables with `partition X = m` — that's the M / Power Query partition type, the only kind Enhanced Refresh accepts. Calculated tables, calculation groups, and measure-only tables are silently dropped.
func RebindReport ¶
RebindReport repoints a Report at a different semantic model (dataset). This is the Power BI REST API, not Fabric Core — the base URL is api.powerbi.com. As of 2026-05 the call accepts the same access token we use for Fabric, but Microsoft documents the Power BI audience separately; if rebind starts returning 401/403, the fix is to expand the requested scopes in auth.go to include "https://analysis.windows.net/powerbi/api/.default".
Returns nil on success. Rebind is synchronous — no polling.
func RunNotebook ¶
func RunNotebook(token, workspaceID, itemID string, inputs []JobInput, lakehouse *DefaultLakehouse) (string, error)
RunNotebook triggers an on-demand notebook job and returns the job instance URL (from the 202 Location header) so callers can poll for completion.
Uses the generic Core endpoint `/items/{id}/jobs/instances?jobType=RunNotebook` — the same one Microsoft's own fabric-cli uses. The release-format `/notebooks/{id}/jobs/execute/instances` endpoint accepts the request (returns 202) but silently ignores parameters, at least as of April 2026.
Body shape (from fabric-cli's ITJobMap comment in fab_types.py):
{
"executionData": {
"parameters": {
"param_name": {"value": <typed>, "type": "string|bool|int|float"}
},
"configuration": {
"defaultLakehouse": {"name": ..., "id": ..., "workspaceId": ...}
}
}
}
lakehouse is optional: pass nil to leave the notebook's own metadata binding untouched (the normal case), or a resolved DefaultLakehouse to override the session's default lakehouse for this run — used to repair notebooks whose binding pins a lakehouse but lost its workspace id.
func SetProfile ¶
func SetProfile(p string)
SetProfile remembers which profile to refresh against on a 401 retry. Called automatically by GetAccessToken — manual callers shouldn't need to touch it.
func SetUserAgent ¶
func SetUserAgent(v string)
SetUserAgent lets main.go install the build version. Called at startup before any HTTP traffic.
func TriggerRefresh ¶
TriggerRefresh kicks off an Enhanced Refresh job. If tables is nil/empty, the entire model is refreshed; otherwise only the named tables. Returns the requestID, parsed from the Location header — that's the handle we poll PollRefreshStatus with.
func UpdateItemDefinition ¶
func UpdateItemDefinition(token, workspaceID, itemID string, def *Definition) error
UpdateItemDefinition replaces the definition of an existing item. Used by the move flow's "overwrite" branch so the destination item's ID survives — preserving incoming bindings (e.g. reports already pointing at this semantic model). Async same as CreateItem; reuses the 5-minute cap.
Types ¶
type Dataset ¶
Dataset is a Power BI semantic model (dataset) as returned by the Power BI /datasets endpoint. Fabric ItemsByType("SemanticModel") returns Items, which we adapt to this shape in ListDatasets so the refresh flow stays decoupled from the generic Item type.
func ListDatasets ¶
ListDatasets returns all semantic models in a workspace via Fabric ListItemsByType. We funnel through the Fabric Items API rather than the Power BI /datasets endpoint so the same Fabric token + workspace resolution path is reused; Fabric guarantees SemanticModel.ID equals the Power BI dataset ID for downstream refresh calls.
type DefaultLakehouse ¶ added in v0.2.0
type DefaultLakehouse struct {
Name string `json:"name,omitempty"`
ID string `json:"id"`
WorkspaceID string `json:"workspaceId"`
}
DefaultLakehouse is the per-run lakehouse override sent under executionData.configuration.defaultLakehouse. Supplying it mounts the named lakehouse for this one job, overriding whatever (possibly broken) binding the notebook carries in its own metadata. Used to repair notebooks that pin a lakehouse GUID but lost the workspace id — see ResolveDefaultLakehouse in the run flow. Shape mirrors fabric-cli / the %%configure magic ({name, id, workspaceId}); the generic REST reference treats executionData as job-type-opaque, so this is the notebook-job-specific schema in practice.
type Definition ¶
type Definition struct {
Parts []DefinitionPart `json:"parts"`
}
Definition is Fabric's item-definition envelope. Returned by getDefinition and accepted by createItem / updateItemDefinition. Each part is a base64 payload identified by a relative path (e.g. "notebook-content.ipynb", "report.json", "model.bim").
func GetItemDefinition ¶
func GetItemDefinition(token, workspaceID, itemID, format string) (*Definition, error)
GetItemDefinition fetches the full definition of any Fabric item. format is forwarded as ?format=… when non-empty (notebooks need "ipynb"; reports and semantic models use "" for the default).
Fabric's getDefinition is async: the first POST may return 202 + Location, which is polled to completion. The 60-attempt cap in pollOperation (2 minutes) is sufficient for getDefinition; large items are handled by the longer cap on CreateItem in Task 6.
type DefinitionPart ¶
type DefinitionPart struct {
Path string `json:"path"`
Payload string `json:"payload"`
PayloadType string `json:"payloadType"`
}
DefinitionPart is one file inside an item definition. PayloadType is almost always "InlineBase64" in practice but Fabric reserves other values, so callers should not assume.
type Item ¶
type Item struct {
ID string `json:"id"`
DisplayName string `json:"displayName"`
Type string `json:"type"`
WorkspaceID string `json:"workspaceId"`
}
Item is a generic Fabric item. Type is "Notebook", "SemanticModel", etc.
func CreateItem ¶
func CreateItem(token, workspaceID, displayName, itemType string, def *Definition) (Item, error)
CreateItem creates a new item in a workspace with the given definition. Returns the new Item (with its ID) so callers can immediately follow up — most notably to rebind a freshly created Report. The call is async: 202 + Location is polled to completion. The 5-minute cap handles large report definitions that the default 2-minute cap would time out on.
func FindNotebookByName ¶
FindNotebookByName returns the notebook with the given displayName, or error if zero or more than one match. Exact match, case-sensitive — same as Fabric.
func ListItems ¶
ListItems returns every item in a workspace, regardless of type. Paging is handled internally via continuationUri. Used by the Move flow to show a single mixed-type picker (then filtered client-side to the supported subset).
func ListItemsByType ¶
ListItemsByType returns items of a specific type ("Notebook", "Report", "SemanticModel", etc.). Same paging as ListItems. Use this when you only need one type — saves filtering client-side when the workspace has many items of other types.
func ListNotebooks ¶
ListNotebooks returns all notebook items in a workspace. Thin wrapper over ListItemsByType for backward compatibility.
type JobInput ¶
JobInput is one parameter sent to a RunNotebook job. Type must be one of the fabric.Type* constants ("string", "bool", "int", "float"). Value is a typed Go value — marshalled as-is, so use string for "string", bool for "bool", int64/int for "int", float64 for "float".
Name is not serialised here — the wire format keys parameters by name using the Name as the map key (see paramValue + RunNotebook body).
type JobInstanceStatus ¶
type JobInstanceStatus struct {
Status string `json:"status"`
StartTimeUtc string `json:"startTimeUtc"`
EndTimeUtc string `json:"endTimeUtc"`
FailureReason any `json:"failureReason"`
RootActivityID string `json:"rootActivityId"`
}
JobInstanceStatus is the minimal shape we care about when polling a job.
func GetJobInstance ¶
func GetJobInstance(token, instanceURL string) (JobInstanceStatus, error)
GetJobInstance fetches current status of a job instance by its URL (returned from RunNotebook).
func (JobInstanceStatus) IsTerminal ¶
func (s JobInstanceStatus) IsTerminal() bool
IsTerminal reports whether a JobInstanceStatus has reached a state where further polling is pointless.
type LakehouseBinding ¶ added in v0.2.0
type LakehouseBinding struct {
// LakehouseID is metadata.default_lakehouse — the lakehouse item GUID,
// or "" when the notebook pins no default lakehouse at all.
LakehouseID string
Name string
// WorkspaceID is the lakehouse's home workspace. Empty is the broken
// state we detect and repair.
WorkspaceID string
}
LakehouseBinding mirrors the default-lakehouse fields a Fabric notebook stores under metadata.dependencies.lakehouse. Git-committed notebooks frequently ship with Name and WorkspaceID empty while LakehouseID still holds a GUID — the workspace id is environment-specific, so authoring or deployment tooling leaves it blank. That half-filled state runs fine interactively (the portal backfills the current workspace) but fails a headless job submit at session attach: "LakehouseWorkspaceId is not a valid GUID".
func ParseLakehouseBinding ¶ added in v0.2.0
func ParseLakehouseBinding(content []byte) (LakehouseBinding, error)
ParseLakehouseBinding extracts the default-lakehouse binding from a Fabric notebook's .ipynb metadata. Returns a zero binding (not an error) when the notebook declares no lakehouse dependency — same "absence is not failure" contract as ParseParameters.
func (LakehouseBinding) NeedsWorkspaceResolution ¶ added in v0.2.0
func (b LakehouseBinding) NeedsWorkspaceResolution() bool
NeedsWorkspaceResolution reports the specific broken-binding pattern worth repairing: a lakehouse is pinned but its workspace id is missing. A complete binding (both set) and a notebook with no lakehouse at all (both empty) both return false — callers should leave those untouched.
type Parameter ¶
type Parameter struct {
Name string
Type string
Default any
// RawDefault is the literal text from the notebook source (e.g. `"foo"`,
// `False`, `42`). Kept for display in the TUI so the user sees exactly
// what was declared.
RawDefault string
}
Parameter describes a discovered notebook parameter. Default holds the literal parsed from the notebook's parameters cell. Type is one of the four lowercase Python-style names that Fabric's RunNotebook job actually accepts on the wire: "string", "bool", "int", "float". (Microsoft Learn documents PascalCase Text/Boolean/Integer/Number for the generic release API — but Microsoft's own fabric-cli uses these lowercase names against the Core endpoint, and that's what works in practice.)
func ParseNotebookParameters ¶
ParseNotebookParameters is a convenience helper: fetches the .ipynb and parses its parameters cell in one call.
func ParseParameters ¶
ParseParameters reads a Fabric notebook's .ipynb content and extracts the parameters declared in the cell tagged "parameters" (Papermill convention).
Returns an empty slice (not an error) if no parameters cell exists or the cell contains no recognisable declarations — callers decide whether that means "no parameters" or "prompt the user for free-form input".
type RefreshMessage ¶
type RefreshMessage struct {
Message string `json:"message"`
}
type RefreshStatus ¶
type RefreshStatus struct {
Status string `json:"status"`
Messages []RefreshMessage `json:"messages,omitempty"`
}
RefreshStatus mirrors the subset of the Enhanced Refresh status payload the UI actually surfaces. Messages are populated on Failed/Cancelled so the user has a hint about what blew up.
func PollRefreshStatus ¶
func PollRefreshStatus(token, workspaceID, datasetID, requestID string) (RefreshStatus, error)
PollRefreshStatus fetches the current status of a refresh request. One call, no polling — callers compose this into a loop or use WaitForRefresh.
func WaitForRefresh ¶
func WaitForRefresh(token, workspaceID, datasetID, requestID string, pollInterval, timeout time.Duration) (RefreshStatus, error)
WaitForRefresh polls until the refresh reaches a terminal state or the timeout expires. 5s interval + 30min timeout matches frefresh's defaults — long-running models can take 20+ minutes, so the timeout is generous.
Transient PollRefreshStatus errors (network blip, single 5xx) are tolerated up to maxTransient consecutive failures before giving up. The refresh continues server-side regardless of polling outcome; a single dropped packet shouldn't abort a 30-minute wait.
type Workspace ¶
Workspace is a minimal projection of the Fabric workspace resource.
func ListWorkspaces ¶
ListWorkspaces returns every workspace the authenticated user can see, paging through Fabric's continuationUri internally. Used for workspace discovery in the customer-edit flow.