Skip to main content

Triggers

The SMB listener polls a directory on a share at a configurable interval and dispatches each file it finds to the matching handler on an attached service. When a tracked file disappears, the deletion handler is called instead.

Three components work together:

ComponentRole
smb:ListenerPolls the share on a schedule and routes file events to services
smb:ServiceDeclares the handler methods that receive file content and metadata
smb:CallerThe share connection passed to a handler, allowing it to read or write other files while processing the current one

For action-based operations, see the Action Reference.


Listener​

The smb:Listener establishes the connection and manages the polling schedule.

Configuration​

ListenerConfiguration fields:

FieldTypeDefaultDescription
hoststring"localhost"Target SMB server hostname or IP address
portint445Port number of the SMB service
sharestringRequiredSMB share name to connect to
authAuthConfiguration—Authentication credentials for the SMB connection
fileNamePatternstring—Regular expression a file name must match to trigger any handler
pollingIntervaldecimal60Seconds between directory polls
dialectsDialect[]All dialectsSMB protocol dialects to negotiate, in order of preference
signRequiredbooleanfalseWhether SMB message signing is required
encryptDatabooleanfalseWhether to encrypt SMB data
enableDfsbooleanfalseWhether to enable Distributed File System (DFS) support
bufferSizeint65536Buffer size for read/write operations in bytes
connectTimeoutdecimal30.0Connection timeout in seconds
laxDataBindingbooleanfalseWhether to relax data binding for XML, JSON, and CSV content
csvFailSafeFailSafeOptions—Skip malformed CSV rows and log them instead of failing the operation

Initializing the listener​

NTLMv2 credentials:

listener smb:Listener smbListener = check new ({
host: "smb.example.com",
share: "reports",
pollingInterval: 10,
auth: {
credentials: {
username: "alice",
password: "***",
domain: "WORKGROUP"
}
}
});

Kerberos authentication:

listener smb:Listener smbListener = check new ({
host: "smb.example.com",
share: "reports",
auth: {
kerberosConfig: {
principal: "[email protected]",
keytab: "/path/to/alice.keytab",
configFile: "/etc/krb5.conf"
}
}
});

With CSV fail-safe enabled:

listener smb:Listener smbListener = check new ({
host: "smb.example.com",
share: "reports",
csvFailSafe: {contentType: smb:RAW_AND_METADATA}
});

Service​

A service is attached to the listener via on smbListener and watches one directory. The @smb:ServiceConfig annotation sets the directory path. The listener descends into subdirectories of that path.

A service must declare at least one onFile* or onFileDelete method.

Callbacks​

The listener picks the handler that matches the incoming file's extension, reads the file, and binds its content to the type declared by the first parameter. If no matching handler is declared, the file falls through to onFile.

CallbackMatched extensionsAccepted content types
onFileText.txt, .log, .mdstring
onFileJson.jsonjson, a record type
onFileXml.xmlxml, a record type
onFileCsv.csvstring[][], a record array, stream<string[], error?>, a stream of records
onFileEverything else; fallback for the abovebyte[], stream<byte[], error?>
onFileDelete(file deleted)string path of the deleted file
onError(listener or handler error)error or smb:Error

After the content parameter, any handler may declare up to two additional parameters in either order:

  • smb:FileInfo — name, path, size, timestamps, and attributes of the file
  • smb:Caller — the share connection, for reading or writing other files during processing

onFileDelete does not receive smb:FileInfo (the file is already gone); it may receive an optional smb:Caller.

Individual handlers can be annotated with @smb:FunctionConfig to set a per-handler file name pattern and post-processing actions (afterProcess and afterError accept smb:DELETE or a smb:Move record with a moveTo destination path).

Full example​

import ballerina/log;
import ballerina/smb;

listener smb:Listener smbListener = check new ({
host: "smb.example.com",
share: "reports",
pollingInterval: 10,
auth: {
credentials: {
username: "alice",
password: "***",
domain: "WORKGROUP"
}
}
});

type SalesReport record {|
string storeId;
string storeLocation;
string saleDate;
|};

@smb:ServiceConfig {
path: "/sales/new"
}
service "salesProcessor" on smbListener {

@smb:FunctionConfig {
afterProcess: {moveTo: "/sales/processed"},
afterError: {moveTo: "/sales/failed"}
}
remote function onFileJson(SalesReport report, smb:Caller caller, smb:FileInfo fileInfo) returns error? {
log:printInfo(string `Processing ${fileInfo.name} for store ${report.storeId}`);
check caller->putText("/sales/audit.log", fileInfo.name + "\n", smb:APPEND);
}

remote function onFile(stream<byte[], error?> content, smb:FileInfo fileInfo) returns error? {
int total = 0;
check from byte[] chunk in content
do { total += chunk.length(); };
log:printInfo(string `${fileInfo.name}: ${total} bytes (unrecognized format)`);
}

remote function onFileDelete(string path, smb:Caller caller) returns error? {
check caller->putText("/sales/deletions.log", path + "\n", smb:APPEND);
}

remote function onError(smb:Error err) returns error? {
log:printError("SMB listener failure", err);
}
}

Supporting Types​

FileInfo​

FieldTypeDescription
namestringName of the file or directory
pathstringRelative file path on the share
sizeintSize of the file in bytes
modifiedAttime:UtcLast modified time in UTC
createdAttime:UtcFile creation time in UTC
accessedAttime:UtcLast access time in UTC
writtenAttime:UtcLast write time in UTC
isDirectorybooleantrue if the resource is a directory
extensionstringFile name extension
isExecutablebooleantrue if the file has execute permissions
isHiddenbooleantrue if the file is marked as hidden
isWritablebooleantrue if the file has write permissions
uristringAbsolute URI of the file

AuthConfiguration​

FieldTypeDescription
credentialsCredentialsNTLMv2 username, password, and domain
kerberosConfigKerberosConfigKerberos principal and keytab configuration

Credentials​

FieldTypeDescription
usernamestringUsername for SMB authentication
passwordstringPassword for SMB authentication
domainstringDomain for domain-based authentication (default: "WORKGROUP")

KerberosConfig​

FieldTypeDescription
principalstringKerberos principal name in user@REALM format
keytabstringPath to the keytab file; the password is used when not provided
configFilestringPath to the Kerberos configuration file (krb5.conf)

FailSafeOptions​

FieldTypeDescription
contentTypeMETADATA | RAW | RAW_AND_METADATAWhat to record in the error log for each skipped CSV row (default: METADATA)