or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

app-management.mdauthentication.mdfirestore.mdfunctions.mdindex.mdmachine-learning.mdmessaging.mdproject-management.mdrealtime-database.mdremote-config.mdstorage.mdtenant-management.md

functions.mddocs/

0

# Cloud Functions

1

2

Firebase Cloud Functions integration for enqueueing tasks in Cloud Task queues associated with callable functions. Enables server-side task scheduling and background processing.

3

4

## Capabilities

5

6

### Task Queue Management

7

8

Get task queue instances for enqueueing background tasks to Cloud Functions.

9

10

```python { .api }

11

def task_queue(function_name, extension_id=None, app=None):

12

"""

13

Get a TaskQueue instance for the specified function.

14

15

Args:

16

function_name: Name of the Cloud Function to target

17

extension_id: Extension ID for extension functions (optional)

18

app: Firebase app instance (optional)

19

20

Returns:

21

TaskQueue: Task queue instance for the specified function

22

"""

23

```

24

25

### Task Operations

26

27

Enqueue and manage tasks for execution by Cloud Functions.

28

29

```python { .api }

30

class TaskQueue:

31

"""Task queue for a specific Cloud Function."""

32

33

def enqueue(self, task_data, opts=None):

34

"""

35

Enqueue a task for execution by the Cloud Function.

36

37

Args:

38

task_data: JSON-serializable data to pass to the function

39

opts: TaskOptions instance for task configuration (optional)

40

41

Returns:

42

str: Task ID for the enqueued task

43

"""

44

45

def delete(self, task_id):

46

"""

47

Delete a task from the queue before it executes.

48

49

Args:

50

task_id: ID of the task to delete

51

"""

52

53

class TaskOptions:

54

"""Configuration options for task enqueueing."""

55

56

def __init__(self, schedule_time=None, dispatch_deadline=None, task_id=None):

57

"""

58

Initialize task options.

59

60

Args:

61

schedule_time: When to execute the task (datetime, optional)

62

dispatch_deadline: Maximum execution time (timedelta, optional)

63

task_id: Custom task ID (string, optional)

64

"""

65

```

66

67

## Usage Examples

68

69

### Basic Task Enqueueing

70

71

```python

72

from firebase_admin import functions

73

import datetime

74

75

# Get task queue for a function

76

queue = functions.task_queue('processOrder')

77

78

# Enqueue a task with data

79

task_data = {

80

'order_id': 'order_123',

81

'user_id': 'user_456',

82

'items': [

83

{'product_id': 'prod_1', 'quantity': 2},

84

{'product_id': 'prod_2', 'quantity': 1}

85

]

86

}

87

88

task_id = queue.enqueue(task_data)

89

print(f'Enqueued task: {task_id}')

90

```

91

92

### Scheduled Task Execution

93

94

```python

95

from firebase_admin import functions

96

from datetime import datetime, timedelta

97

98

# Schedule task for future execution

99

queue = functions.task_queue('sendReminders')

100

101

# Execute task in 1 hour

102

schedule_time = datetime.utcnow() + timedelta(hours=1)

103

opts = functions.TaskOptions(schedule_time=schedule_time)

104

105

task_data = {

106

'reminder_type': 'payment_due',

107

'user_id': 'user_789',

108

'due_date': '2024-01-15'

109

}

110

111

task_id = queue.enqueue(task_data, opts=opts)

112

print(f'Scheduled task: {task_id} for {schedule_time}')

113

```

114

115

### Task Configuration Options

116

117

```python

118

from firebase_admin import functions

119

from datetime import datetime, timedelta

120

121

queue = functions.task_queue('processLargeFile')

122

123

# Configure task with custom options

124

opts = functions.TaskOptions(

125

schedule_time=datetime.utcnow() + timedelta(minutes=30),

126

dispatch_deadline=timedelta(minutes=10), # Max 10 minutes to complete

127

task_id='file_process_custom_id_123' # Custom task ID

128

)

129

130

task_data = {

131

'file_url': 'gs://my-bucket/large-file.csv',

132

'processing_options': {

133

'format': 'csv',

134

'delimiter': ',',

135

'headers': True

136

}

137

}

138

139

task_id = queue.enqueue(task_data, opts=opts)

140

print(f'Configured task: {task_id}')

141

```

142

143

### Extension Functions

144

145

```python

146

# For Firebase Extension functions

147

queue = functions.task_queue(

148

function_name='processImage',

149

extension_id='firebase/storage-resize-images'

150

)

151

152

task_data = {

153

'image_path': 'uploads/photo.jpg',

154

'sizes': [100, 300, 600]

155

}

156

157

task_id = queue.enqueue(task_data)

158

```

159

160

### Task Management

161

162

```python

163

# Enqueue task and potentially cancel it

164

queue = functions.task_queue('longRunningProcess')

165

166

task_data = {'data_to_process': 'large_dataset_id'}

167

task_id = queue.enqueue(task_data)

168

169

# Later, if needed, delete the task before it executes

170

try:

171

queue.delete(task_id)

172

print(f'Cancelled task: {task_id}')

173

except Exception as e:

174

print(f'Could not cancel task: {e}')

175

# Task may have already started or completed

176

```

177

178

### Batch Task Enqueueing

179

180

```python

181

# Enqueue multiple related tasks

182

queue = functions.task_queue('processUserData')

183

184

users_to_process = ['user1', 'user2', 'user3', 'user4']

185

task_ids = []

186

187

for user_id in users_to_process:

188

task_data = {

189

'user_id': user_id,

190

'operation': 'update_profile',

191

'batch_id': 'batch_001'

192

}

193

194

task_id = queue.enqueue(task_data)

195

task_ids.append(task_id)

196

197

print(f'Enqueued {len(task_ids)} tasks for batch processing')

198

```

199

200

### Error Handling

201

202

```python

203

from firebase_admin import functions

204

from firebase_admin.exceptions import FirebaseError

205

206

try:

207

queue = functions.task_queue('nonexistentFunction')

208

task_id = queue.enqueue({'data': 'test'})

209

except FirebaseError as e:

210

print(f'Failed to enqueue task: {e}')

211

except Exception as e:

212

print(f'Unexpected error: {e}')

213

214

# Handle task deletion errors

215

try:

216

queue.delete('invalid_task_id')

217

except FirebaseError as e:

218

if 'NOT_FOUND' in str(e):

219

print('Task not found or already completed')

220

else:

221

print(f'Error deleting task: {e}')

222

```

223

224

## Cloud Function Integration

225

226

### Function Implementation

227

228

The Cloud Functions that receive these tasks should be implemented to handle the enqueued data:

229

230

```javascript

231

// Example Cloud Function (Node.js)

232

const functions = require('firebase-functions');

233

234

exports.processOrder = functions.tasks.taskQueue({

235

retryConfig: {

236

maxAttempts: 3,

237

minBackoffSeconds: 60,

238

},

239

rateLimits: {

240

maxConcurrentDispatches: 10,

241

},

242

}).onDispatch(async (data) => {

243

const { order_id, user_id, items } = data;

244

245

// Process the order

246

console.log(`Processing order ${order_id} for user ${user_id}`);

247

248

// Your order processing logic here

249

for (const item of items) {

250

console.log(`Processing item: ${item.product_id}, quantity: ${item.quantity}`);

251

}

252

253

return { success: true, processed_at: new Date().toISOString() };

254

});

255

```

256

257

### Task Queue Configuration

258

259

Task queues can be configured with various options in the Cloud Function:

260

261

```javascript

262

// Advanced task queue configuration

263

exports.processLargeFile = functions.tasks.taskQueue({

264

retryConfig: {

265

maxAttempts: 5,

266

minBackoffSeconds: 120,

267

maxBackoffSeconds: 3600,

268

maxDoublings: 3,

269

},

270

rateLimits: {

271

maxConcurrentDispatches: 5,

272

maxDispatchesPerSecond: 1,

273

},

274

invoker: ['service-account@project.iam.gserviceaccount.com'],

275

}).onDispatch(async (data) => {

276

// Handle large file processing

277

const { file_url, processing_options } = data;

278

// Processing logic here

279

});

280

```

281

282

## Best Practices

283

284

### Task Design

285

286

- **Idempotent Operations**: Design tasks to be safely retryable

287

- **Appropriate Payload Size**: Keep task data reasonably sized

288

- **Error Handling**: Implement proper error handling in Cloud Functions

289

- **Monitoring**: Monitor task queue metrics and function execution

290

291

### Performance Optimization

292

293

- **Batch Related Operations**: Group related tasks when possible

294

- **Configure Retry Policies**: Set appropriate retry configurations

295

- **Rate Limiting**: Configure rate limits based on downstream dependencies

296

- **Resource Management**: Size functions appropriately for task complexity

297

298

### Security Considerations

299

300

- **Validate Task Data**: Always validate incoming task data in functions

301

- **Access Control**: Use IAM roles to control who can enqueue tasks

302

- **Data Sensitivity**: Avoid including sensitive data in task payloads

303

- **Authentication**: Ensure proper authentication for task enqueueing

304

305

## Monitoring and Debugging

306

307

### Task Queue Metrics

308

309

Monitor task queue performance through Firebase Console:

310

311

- Task success/failure rates

312

- Queue depth and processing times

313

- Function execution metrics

314

- Error rates and types

315

316

### Logging and Debugging

317

318

```python

319

import logging

320

from firebase_admin import functions

321

322

# Enable detailed logging

323

logging.basicConfig(level=logging.DEBUG)

324

325

# Enqueue task with debugging info

326

queue = functions.task_queue('debugFunction')

327

task_data = {

328

'debug_info': {

329

'enqueued_at': datetime.utcnow().isoformat(),

330

'source': 'admin_script',

331

'version': '1.0'

332

},

333

'actual_data': {'key': 'value'}

334

}

335

336

task_id = queue.enqueue(task_data)

337

logging.info(f'Debug task enqueued: {task_id}')

338

```

339

340

## Types

341

342

```python { .api }

343

class TaskQueue:

344

"""Task queue for a specific Cloud Function."""

345

346

def enqueue(self, task_data, opts=None):

347

"""Enqueue a task for execution."""

348

349

def delete(self, task_id):

350

"""Delete a task from the queue."""

351

352

class TaskOptions:

353

"""Configuration options for task enqueueing."""

354

355

def __init__(self, schedule_time=None, dispatch_deadline=None, task_id=None):

356

"""

357

Initialize task options.

358

359

Args:

360

schedule_time: When to execute the task (datetime)

361

dispatch_deadline: Maximum execution time (timedelta)

362

task_id: Custom task ID (string)

363

"""

364

```