Files
Microsoft-Rewards-Script/docs/jobstate.md
Light 15f62963f8 V2 (#365)
* first commit

* Addition of a personalized activity manager and refactoring of the logic of activities

* Adding diagnostics management, including screenshot and HTML content, as well as improvements to humanize page interactions and +.

* Adding the management of newspapers and webhook settings, including filtering messages and improving the structure of the summaries sent.

* Adding a post-execution auto-date functionality, including options to update via Git and Docker, as well as a new configuration interface to manage these parameters.

* Adding accounts in Docker, with options to use an environmental file or online JSON data, as well as minimum validations for responsible accounts.

* Improving the Microsoft Rewards script display with a new headband and better log management, including colors and improved formatting for the console.

* v2

* Refactor ESLint configuration and scripts for improved TypeScript support and project structure

* Addition of the detection of suspended accounts with the gesture of the improved errors and journalization of banishment reasons

* Adding an integrated planner for programmed task execution, with configuration in Config.json and +

* Edit

* Remove texte

* Updating of documentation and adding the management of humanization in the configuration and +.

* Adding manual purchase method allowing users to spend points without automation, with monitoring of expenses and notifications.

* Correction of documentation and improvement of configuration management for manual purchase mode, adding complete documentation and appropriate banner display.

* Add comprehensive documentation for job state persistence, NTFY notifications, proxy configuration, scheduling, and auto-update features

- Introduced job state persistence documentation to track progress and resume tasks.
- Added NTFY push notifications integration guide for real-time alerts.
- Documented proxy configuration options for enhanced privacy and network management.
- Included scheduling configuration for automated script execution.
- Implemented auto-update configuration to keep installations current with Git and Docker options.

* Ajout d'Unt Système de Rapport d'Erreurs Communautaire pour Améliorerer le Débogage, incluant la Configuration et l'Envoi de Résumés D'Erreurs Anonyés à un webhook Discord.

* Mini Edit

* Mise à Jour du Readme.md pour Améliorerer la Présentation et La Claté, Ajout d'Un section sur les notifications en Temps Raine et Mise à Jour des badges pour la meille unibilité.

* Documentation update

* Edit README.md

* Edit

* Update README with legacy version link

* Improvement of location data management and webhooks, adding configurations normalization

* Force update for PR

* Improvement of documentation and configuration options for Cron integration and Docker use

* Improvement of planning documentation and adding a multi-pan-pancake in the daily execution script

* Deletion of the CommunityReport functionality in accordance with the project policy

* Addition of randomization of start -up schedules and surveillance time for planner executions

* Refactor Docker setup to use built-in scheduler, removing cron dependencies and simplifying configuration options

* Adding TOTP support for authentication, update of interfaces and configuration files to include Totp secret, and automatic generation of the Totp code when connecting.

* Fix [LOGIN-NO-PROMPT] No dialogs (xX)

* Reset the Totp field for email_1 in the accounts.example.json file

* Reset the Totp field for email_1 in the Readme.md file

* Improvement of Bing Research: Use of the 'Attacked' method for the research field, management of overlays and adding direct navigation in the event of entry failure.

* Adding a complete security policy, including directives on vulnerability management, coordinated disclosure and user security advice.

* Remove advanced environment variables section from README

* Configuration and dockerfile update: Passage to Node 22, addition of management of the purchase method, deletion of obsolete scripts

* Correction of the order of the sections in the Readme.md for better readability

* Update of Readm and Security Policy: Addition of the method of purchase and clarification of security and confidentiality practices.

* Improvement of the readability of the Readm and deletion of the mention of reporting of vulnerabilities in the security document.

* Addition of humanization management and adaptive throttling to simulate more human behavior in bot activities.

* Addition of humanization management: activation/deactivation of human gestures, configuration update and adding documentation on human mode.

* Deletion of community error report functionality to respect the privacy policy

* Addition of immediate banning alerts and vacation configuration in the Microsoft Rewards bot

* Addition of immediate banning alerts and vacation configuration in the Microsoft Rewards bot

* Added scheduling support: support for 12h and 24h formats, added options for time zone, and immediate execution on startup.

* Added window size normalization and page rendering to fit typical screens, with injected CSS styles to prevent excessive zooming.

* Added security incident management: detection of hidden recovery emails, automation blocking, and global alerts. Updated configuration files and interfaces to include recovery emails. Improved security incident documentation.

* Refactor incident alert handling: unified alert sender

* s

* Added security incident management: detect recovery email inconsistencies and send unified alerts. Implemented helper methods to manage alerts and compromised modes.

* Added heartbeat management for the scheduler: integrated a heartbeat file to report liveliness and adjusted the watchdog configuration to account for heartbeat updates.

* Edit webook

* Updated security alert management: fixed the recovery email hidden in the documentation and enabled the conclusion webhook for notifications.

* Improved security alert handling: added structured sending to webhooks for better visibility and updated callback interval in compromised mode.

* Edit conf

* Improved dependency installation: Added the --ignore-scripts option for npm ci and npm install. Updated comments in compose.yaml for clarity.

* Refactor documentation structure and enhance logging:
- Moved documentation files from 'information' to 'docs' directory for better organization.
- Added live logging configuration to support webhook logs with email redaction.
- Updated file paths in configuration and loading functions to accommodate new structure.
- Adjusted scheduler behavior to prevent immediate runs unless explicitly set.
- Improved error handling for account and config file loading.
- Enhanced security incident documentation with detailed recovery steps.

* Fix docs

* Remove outdated documentation on NTFY, Proxy, Scheduling, Security, and Auto-Update configurations; update Browser class to prioritize headless mode based on environment variable.

* Addition of documentation for account management and Totp, Docker Guide, and Update of the Documentation Index.

* Updating Docker documentation: simplification of instructions and adding links to detailed guides. Revision of configuration options and troubleshooting sections.

* Edit

* Edit docs

* Enhance documentation for Scheduler, Security, and Auto-Update features

- Revamped the Scheduler documentation to include detailed features, configuration options, and usage examples.
- Expanded the Security guide with comprehensive incident response strategies, privacy measures, and monitoring practices.
- Updated the Auto-Update section to clarify configuration, methods, and best practices for maintaining system integrity.

* Improved error handling and added crash recovery in the Microsoft Rewards bot. Added configuration for automatic restart and handling of local search queries when trends fail.

* Fixed initial point counting in MicrosoftRewardsBot and improved error handling when sending summaries to webhooks.

* Added unified support for notifications and improved handling of webhook configurations in the normalizeConfig and log functions.

* UPDATE LOGIN

* EDIT LOGIN

* Improved login error handling: added recovery mismatch detection and the ability to switch to password authentication.

* Added a full reference to configuration in the documentation and improved log and error handling in the code.

* Added context management for conclusion webhooks and improved user configuration for notifications.

* Mini edit

* Improved logic for extracting masked emails for more accurate matching during account recovery.
2025-09-26 18:58:33 +02:00

339 lines
8.6 KiB
Markdown

# 💾 Job State Persistence
<div align="center">
**🔄 Resume interrupted tasks and track progress across runs**
*Never lose your progress again*
</div>
---
## 🎯 What is Job State Persistence?
Job state persistence allows the script to **resume interrupted tasks** and **track progress** across multiple runs, ensuring no work is lost when the script is stopped or crashes.
### **Key Features**
- 🔄 **Resumable tasks** — Pick up exactly where you left off
- 📅 **Daily tracking** — Date-specific progress monitoring
- 👤 **Per-account isolation** — Independent progress for each account
- 🛡️ **Corruption protection** — Atomic writes prevent data loss
- 🚀 **Performance optimized** — Minimal overhead
---
## ⚙️ Configuration
### **Basic Setup**
```json
{
"jobState": {
"enabled": true,
"dir": ""
}
}
```
### **Configuration Options**
| Setting | Description | Default |
|---------|-------------|---------|
| `enabled` | Enable job state persistence | `true` |
| `dir` | Custom directory for state files | `""` (uses `sessions/job-state`) |
---
## 🏗️ How It Works
### **State Tracking**
- 📋 **Monitors completion** status of individual activities
- 🔍 **Tracks progress** for daily sets, searches, and promotional tasks
-**Prevents duplicates** when script restarts
### **Storage Structure**
```
sessions/job-state/
├── account1@email.com/
│ ├── daily-set-2025-01-20.json
│ ├── desktop-search-2025-01-20.json
│ └── mobile-search-2025-01-20.json
└── account2@email.com/
├── daily-set-2025-01-20.json
└── promotional-tasks-2025-01-20.json
```
### **State File Format**
```json
{
"date": "2025-01-20",
"account": "user@email.com",
"type": "daily-set",
"completed": [
"daily-check-in",
"quiz-1",
"poll-1"
],
"remaining": [
"quiz-2",
"search-desktop"
],
"lastUpdate": "2025-01-20T10:30:00.000Z"
}
```
---
## 🚀 Key Benefits
### **Resumable Tasks**
-**Script restarts** pick up where they left off
-**Individual completion** is remembered
-**Avoid re-doing** completed activities
### **Daily Reset**
- 📅 **Date-specific** state files
- 🌅 **New day** automatically starts fresh tracking
- 📚 **History preserved** for analysis
### **Account Isolation**
- 👤 **Separate state** per account
-**Parallel processing** doesn't interfere
- 📊 **Independent progress** tracking
---
## 📋 Use Cases
### **Interrupted Executions**
| Scenario | Benefit |
|----------|---------|
| **Network issues** | Resume when connection restored |
| **System reboots** | Continue after restart |
| **Manual termination** | Pick up from last checkpoint |
| **Resource exhaustion** | Recover without losing progress |
### **Selective Reruns**
| Feature | Description |
|---------|-------------|
| **Skip completed sets** | Avoid redoing finished daily activities |
| **Resume searches** | Continue partial search sessions |
| **Retry failed tasks** | Target only problematic activities |
| **Account targeting** | Process specific accounts only |
### **Progress Monitoring**
- 📊 **Track completion rates** across accounts
- 🔍 **Identify problematic** activities
- ⏱️ **Monitor task duration** trends
- 🐛 **Debug stuck** or slow tasks
---
## 🛠️ Technical Implementation
### **Checkpoint Strategy**
- 💾 **State saved** after each completed activity
- ⚛️ **Atomic writes** prevent corruption
- 🔒 **Lock-free design** for concurrent access
### **Performance Optimization**
-**Minimal I/O overhead** — Fast state updates
- 🧠 **In-memory caching** — Reduce disk access
- 📥 **Lazy loading** — Load state files on demand
### **Error Handling**
- 🔧 **Corrupted files** are rebuilt automatically
- 📁 **Missing directories** created as needed
- 🎯 **Graceful degradation** when disabled
---
## 🗂️ File Management
### **Automatic Behavior**
- 📅 **Date-specific files** — New files for each day
- 💾 **Preserved history** — Old files remain for reference
- 🚀 **No auto-deletion** — Manual cleanup recommended
### **Manual Maintenance**
```powershell
# Clean state files older than 7 days
Get-ChildItem sessions/job-state -Recurse -Filter "*.json" | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-7)} | Remove-Item
# Reset all job state (start fresh)
Remove-Item -Recurse -Force sessions/job-state/
# Reset specific account state
Remove-Item -Recurse -Force sessions/job-state/user@email.com/
```
---
## 📊 Example Workflows
### **Interrupted Daily Run**
```
Day 1 - 10:30 AM:
✅ Account A: Daily set completed
🔄 Account B: 3/5 daily tasks done
❌ Script crashes
Day 1 - 2:00 PM:
🚀 Script restarts
✅ Account A: Skipped (already complete)
🔄 Account B: Resumes with 2 remaining tasks
```
### **Multi-Day Tracking**
```
Monday:
📅 daily-set-2025-01-20.json created
✅ All tasks completed
Tuesday:
📅 daily-set-2025-01-21.json created
🔄 Fresh start for new day
📚 Monday's progress preserved
```
---
## 🔍 Debugging Job State
### **State Inspection**
```powershell
# View current state for account
Get-Content sessions/job-state/user@email.com/daily-set-2025-01-20.json | ConvertFrom-Json
# List all state files
Get-ChildItem sessions/job-state -Recurse -Filter "*.json"
```
### **Debug Output**
Enable verbose logging to see state operations:
```powershell
$env:DEBUG_REWARDS_VERBOSE=1; npm start
```
Sample output:
```
[INFO] Loading job state for user@email.com (daily-set)
[INFO] Found 3 completed tasks, 2 remaining
[INFO] Skipping completed task: daily-check-in
[INFO] Starting task: quiz-2
```
---
## 🛠️ Troubleshooting
| Problem | Cause | Solution |
|---------|-------|----------|
| **Tasks not resuming** | Missing/corrupt state files | Check file permissions; verify directory exists |
| **Duplicate execution** | Clock sync issues | Ensure system time is accurate |
| **Excessive files** | No cleanup schedule | Implement regular state file cleanup |
| **Permission errors** | Write access denied | Verify sessions/ directory is writable |
### **Common Issues**
#### **Tasks Not Resuming**
```
[ERROR] Failed to load job state: Permission denied
```
**Solutions:**
- ✅ Check file/directory permissions
- ✅ Verify state directory exists
- ✅ Ensure write access to sessions/
#### **Duplicate Task Execution**
```
[WARN] Task appears to be running twice
```
**Solutions:**
- ✅ Check for corrupt state files
- ✅ Verify system clock synchronization
- ✅ Clear state for affected account
#### **Storage Growth**
```
[INFO] Job state directory: 2.3GB (1,247 files)
```
**Solutions:**
- ✅ Implement regular cleanup schedule
- ✅ Remove old state files (7+ days)
- ✅ Monitor disk space usage
---
## 🤝 Integration Features
### **Session Persistence**
- 🍪 **Works alongside** browser session storage
- 🔐 **Complements** cookie and fingerprint persistence
- 🌐 **Independent of** proxy and authentication state
### **Clustering**
-**Isolated state** per cluster worker
- 🚫 **No shared state** between parallel processes
- 📁 **Worker-specific** directories
### **Scheduling**
-**Persists across** scheduled runs
- 🌅 **Daily reset** at midnight automatically
- 🔄 **Long-running continuity** maintained
---
## ⚙️ Advanced Configuration
### **Custom State Directory**
```json
{
"jobState": {
"enabled": true,
"dir": "/custom/path/to/state"
}
}
```
### **Disabling Job State**
```json
{
"jobState": {
"enabled": false
}
}
```
**Effects when disabled:**
-**Tasks restart** from beginning each run
-**No progress tracking** between sessions
-**Potential duplicate work** on interruptions
-**Slightly faster startup** (no state loading)
---
## 📊 Best Practices
### **Development**
-**Enable for testing** — Consistent behavior
- 🧹 **Clear between changes** — Fresh state for major updates
- 🔍 **Monitor for debugging** — State files reveal execution flow
### **Production**
-**Always enabled** — Reliability is critical
- 💾 **Regular backups** — State directory backups
- 📊 **Monitor disk usage** — Prevent storage growth
### **Maintenance**
- 🗓️ **Weekly cleanup** — Remove old state files
- 🔍 **Health checks** — Verify state integrity
- 📝 **Usage monitoring** — Track storage trends
---
## 🔗 Related Guides
- **[Getting Started](./getting-started.md)** — Initial setup and configuration
- **[Scheduler](./schedule.md)** — Automated timing and execution
- **[Diagnostics](./diagnostics.md)** — Error capture and debugging
- **[Security](./security.md)** — Privacy and data protection