Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat: new app database shape (#2445)

Gergő Móricz3086a2745916
diff --git a/.github/archive/js-sdk.yml b/.github/archive/js-sdk.yml
index e996f7d3b..a468ee637 100644
--- a/.github/archive/js-sdk.yml
+++ b/.github/archive/js-sdk.yml
@@ -8,8 +8,6 @@ env:
FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
HOST: ${{ secrets.HOST }}
LLAMAPARSE_API_KEY: ${{ secrets.LLAMAPARSE_API_KEY }}
- POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
- POSTHOG_HOST: ${{ secrets.POSTHOG_HOST }}
NUM_WORKERS_PER_QUEUE: ${{ secrets.NUM_WORKERS_PER_QUEUE }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PLAYWRIGHT_MICROSERVICE_URL: ${{ secrets.PLAYWRIGHT_MICROSERVICE_URL }}
diff --git a/.github/archive/python-sdk.yml b/.github/archive/python-sdk.yml
index b05ba2eb5..fbafb9709 100644
--- a/.github/archive/python-sdk.yml
+++ b/.github/archive/python-sdk.yml
@@ -8,8 +8,6 @@ env:
FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
HOST: ${{ secrets.HOST }}
LLAMAPARSE_API_KEY: ${{ secrets.LLAMAPARSE_API_KEY }}
- POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
- POSTHOG_HOST: ${{ secrets.POSTHOG_HOST }}
NUM_WORKERS_PER_QUEUE: ${{ secrets.NUM_WORKERS_PER_QUEUE }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PLAYWRIGHT_MICROSERVICE_URL: ${{ secrets.PLAYWRIGHT_MICROSERVICE_URL }}
diff --git a/.github/archive/rust-sdk.yml b/.github/archive/rust-sdk.yml
index fa84726fd..9ec13fe5a 100644
--- a/.github/archive/rust-sdk.yml
+++ b/.github/archive/rust-sdk.yml
@@ -8,8 +8,6 @@ env:
FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
HOST: ${{ secrets.HOST }}
LLAMAPARSE_API_KEY: ${{ secrets.LLAMAPARSE_API_KEY }}
- POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
- POSTHOG_HOST: ${{ secrets.POSTHOG_HOST }}
NUM_WORKERS_PER_QUEUE: ${{ secrets.NUM_WORKERS_PER_QUEUE }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PLAYWRIGHT_MICROSERVICE_URL: ${{ secrets.PLAYWRIGHT_MICROSERVICE_URL }}
diff --git a/.github/workflows/test-server.yml b/.github/workflows/test-server.yml
index 49f420f97..6147e8f62 100644
--- a/.github/workflows/test-server.yml
+++ b/.github/workflows/test-server.yml
@@ -238,7 +238,6 @@ jobs:
# prod-test:
# name: Production environment tests
# runs-on: big-runner
- # needs: audit
# services:
# redis:
# image: redis
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2ffceb70b..494dde2ad 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -65,8 +65,6 @@ BULL_AUTH_KEY= @
PLAYWRIGHT_MICROSERVICE_URL= # set if you'd like to run a playwright fallback
LLAMAPARSE_API_KEY= #Set if you have a llamaparse key you'd like to use to parse pdfs
SLACK_WEBHOOK_URL= # set if you'd like to send slack server health status messages
-POSTHOG_API_KEY= # set if you'd like to send posthog events like job logs
-POSTHOG_HOST= # set if you'd like to send posthog events like job logs
```
diff --git a/SELF_HOST.md b/SELF_HOST.md
index e67e05eca..6f599f253 100644
--- a/SELF_HOST.md
+++ b/SELF_HOST.md
@@ -109,10 +109,6 @@ BULL_AUTH_KEY=CHANGEME
# Set if you'd like to send server health status messages to Slack
# SLACK_WEBHOOK_URL=
-# Set if you'd like to send posthog events like job logs
-# POSTHOG_API_KEY=
-# POSTHOG_HOST=
-
## === System Resource Configuration ===
# Maximum CPU usage threshold (0.0-1.0). Worker will reject new jobs when CPU usage exceeds this value.
# Default: 0.8 (80%)
diff --git a/apps/api/package.json b/apps/api/package.json
index 0fe5a42f6..f98bb74f2 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -80,7 +80,6 @@
"@bull-board/express": "^6.14.0",
"@coinbase/x402": "^0.6.6",
"@dqbd/tiktoken": "^1.0.22",
- "@google-cloud/bigquery": "^8.1.1",
"@google-cloud/storage": "^7.16.0",
"@mendable/firecrawl-rs": "workspace:*",
"@openrouter/ai-sdk-provider": "^0.4.5",
@@ -125,7 +124,6 @@
"parse-diff": "^0.11.1",
"pdf-parse": "^1.1.1",
"pg": "^8.16.3",
- "posthog-node": "^4.0.1",
"prettier": "^3.6.2",
"prom-client": "^15.1.3",
"psl": "^1.15.0",
diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yaml
index bc04fb8d8..61de3f96c 100644
--- a/apps/api/pnpm-lock.yaml
+++ b/apps/api/pnpm-lock.yaml
@@ -50,9 +50,6 @@ importers:
'@dqbd/tiktoken':
specifier: ^1.0.22
version: 1.0.22
- '@google-cloud/bigquery':
- specifier: ^8.1.1
- version: 8.1.1
'@google-cloud/storage':
specifier: ^7.16.0
version: 7.16.0([email protected])
@@ -185,9 +182,6 @@ importers:
pg:
specifier: ^8.16.3
version: 8.16.3([email protected])
- posthog-node:
- specifier: ^4.0.1
- version: 4.0.1
prettier:
specifier: ^3.6.2
version: 3.6.2
@@ -943,26 +937,10 @@ packages:
peerDependencies:
viem: '>=2.0.0'
- '@google-cloud/[email protected]':
- resolution: {integrity: sha512-2GHlohfA/VJffTvibMazMsZi6jPRx8MmaMberyDTL8rnhVs/frKSXVVRtLU83uSAy2j/5SD4mOs4jMQgJPON2g==}
- engines: {node: '>=18'}
-
- '@google-cloud/[email protected]':
- resolution: {integrity: sha512-IXh04DlkLMxWgYLIUYuHHKXKOUwPDzDgke1ykkkJPe48cGIS9kkL2U/o0pm4ankHLlvzLF/ma1eO86n/bkumIA==}
- engines: {node: '>=18'}
-
'@google-cloud/[email protected]':
resolution: {integrity: sha512-DJS3s0OVH4zFDB1PzjxAsHqJT6sKVbRwwML0ZBP9PbU7Yebtu/7SWMRzvO2J3nUi9pRNITCfu4LJeooM2w4pjg==}
engines: {node: '>=14.0.0'}
- '@google-cloud/[email protected]':
- resolution: {integrity: sha512-g5nmMnzC+94kBxOKkLGpK1ikvolTFCC3s2qtE4F+1EuArcJ7HHC23RDQVt3Ra3CqpUYZ+oXNKZ8n5Cn5yug8DA==}
- engines: {node: '>=18'}
-
- '@google-cloud/[email protected]':
- resolution: {integrity: sha512-9h0Gvw92EvPdE8AK8AgZPbMnH5ftDyPtKm7/KUfcJVaPEPjwGDsJd1QV0H8esBDV4II41R/2lDWH1epBqIoKUw==}
- engines: {node: '>=18'}
-
'@google-cloud/[email protected]':
resolution: {integrity: sha512-MmaX6HeSvyPbWGwFq7mXdo0uQZLGBYCwziiLIGq5JVX+/bdI3SAq6bP98trV5eTWfLuvsMcIC1YJOF2vfteLFA==}
engines: {node: '>=14.0.0'}
@@ -971,10 +949,6 @@ packages:
resolution: {integrity: sha512-Orxzlfb9c67A15cq2JQEyVc7wEsmFBmHjZWZYQMUyJ1qivXyMwdyNOs9odi79hze+2zqdTtu1E19IM/FtqZ10g==}
engines: {node: '>=14'}
- '@google-cloud/[email protected]':
- resolution: {integrity: sha512-N8qS6dlORGHwk7WjGXKOSsLjIjNINCPicsOX6gyyLiYk7mq3MtII96NZ9N2ahwA2vnkLmZODOIH9rlNniYWvCQ==}
- engines: {node: '>=18'}
-
'@google-cloud/[email protected]':
resolution: {integrity: sha512-7/5LRgykyOfQENcm6hDKP8SX/u9XxE5YOiWOkgkwcoO+cG8xT/cyOvp9wwN3IxfdYgpHs8CE7Nq2PKX2lNaEXw==}
engines: {node: '>=14'}
@@ -3737,10 +3711,6 @@ packages:
resolution: {integrity: sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-tLkvA81vQG/XqE2mjDkGQHoOINtMHtysSnemrmoGe6PydDPMRbVugqyk4A6V/WDWEfm3l+0d8anA9r8cv/5Jaw==}
- engines: {node: '>=12'}
-
resolution: {integrity: sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==}
@@ -4162,10 +4132,6 @@ packages:
resolution: {integrity: sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
- resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}
- engines: {node: '>= 12'}
-
resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==}
engines: {node: '>=18'}
@@ -4568,10 +4534,6 @@ packages:
resolution: {integrity: sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==}
- resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}
- engines: {node: ^12.20 || >= 14.13}
-
resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}
@@ -4627,10 +4589,6 @@ packages:
engines: {node: '>=18.3.0'}
hasBin: true
- resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==}
- engines: {node: '>=12.20.0'}
-
resolution: {integrity: sha512-Oz5Hwvwak/DCaXVVUtPn4oLMLLy1CdclLKO1LFgU7XzDpVMUU5UjlSLpGMocyQNNk8F6IJW9M/YdooSn2MRI+Q==}
@@ -4663,18 +4621,10 @@ packages:
resolution: {integrity: sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==}
engines: {node: '>=14'}
- resolution: {integrity: sha512-/Szrn8nr+2TsQT1Gp8iIe/BEytJmbyfrbFh419DfGQSkEgNEhbPi7JRJuughjkTzPWgU9gBQf5AVu3DbHt0OXA==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==}
engines: {node: '>=14'}
- resolution: {integrity: sha512-UcO3kefx6dCcZkgcTGgVOTFb7b1LlQ02hY1omMjjrrBzkajRMCFgYOjs7J71WqnuG1k2b+9ppGL7FsOfhZMQKQ==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
engines: {node: '>=6.9.0'}
@@ -4731,10 +4681,6 @@ packages:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
deprecated: Glob versions prior to v9 are no longer supported
- resolution: {integrity: sha512-ylSE3RlCRZfZB56PFJSfUCuiuPq83Fx8hqu1KPWGK8FVdSaxlp/qkeMMX/DT/18xkwXIHvXEXkZsljRwfrdEfQ==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==}
engines: {node: '>=14'}
@@ -4743,10 +4689,6 @@ packages:
resolution: {integrity: sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==}
engines: {node: '>=14'}
- resolution: {integrity: sha512-rcX58I7nqpu4mbKztFeOAObbomBbHU2oIb/d3tJfF3dizGSApqtSwYJigGCooHdnMyQBIw8BrWyK96w3YXgr6A==}
- engines: {node: '>=14'}
-
resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==}
@@ -4761,10 +4703,6 @@ packages:
resolution: {integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==}
engines: {node: '>=14.0.0'}
- resolution: {integrity: sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-z5cFQWDffyOe4vQ9xIqNfCZdV4p//vy6fBnr8Q1AWnVZ0teurKMG66rLj++TKwKPUP3u7iMUvrvKaEUiQw2QWQ==}
@@ -5589,11 +5527,6 @@ packages:
resolution: {integrity: sha512-qN8v/s2PAJwGUtr1/hYTpNKlD6Y9rc4p8KSmJXyGdYGZsDGKXrGThikLFP9OCHFeLeEpQzPwiAtdIvBLqm//Hw==}
- resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}
- engines: {node: '>=10.5.0'}
- deprecated: Use your platform's native DOMException instead
-
resolution: {integrity: sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw==}
@@ -5609,10 +5542,6 @@ packages:
encoding:
optional: true
- resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==}
- engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
-
resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==}
hasBin: true
@@ -5979,10 +5908,6 @@ packages:
resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-rtqm2h22QxLGBrW2bLYzbRhliIrqgZ0k+gF0LkQ1SNdeD06YE5eilV0MxZppFSxC8TfH0+B0cWCuebEnreIDgQ==}
- engines: {node: '>=15.0.0'}
-
resolution: {integrity: sha512-1cSoF0aCC8uaARATfrlz4VCBqE8LwZwRfLgkxJOQwAlQt6ayTmi0D9OF7nXid1POI5SZidFuG9CnlXbDfLqY/Q==}
@@ -6205,10 +6130,6 @@ packages:
resolution: {integrity: sha512-dUOvLMJ0/JJYEn8NrpOaGNE7X3vpI5XlZS/u0ANjqtcZVKnIxP7IgCFwrKTxENw29emmwug53awKtaMm4i9g5w==}
engines: {node: '>=14'}
- resolution: {integrity: sha512-JzFPAfklk1kjR1w76f0QOIhoDkNkSqW8wYKT08n9yysTmZfB+RQ2QoXoTAeOi1HD9ZipTyTAZg3c4pM/jeqgSw==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}
engines: {node: '>= 4'}
@@ -6233,9 +6154,6 @@ packages:
resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}
- resolution: {integrity: sha512-cLgakCUf6PedEu15t8kbsjnwIFFR2D4RfL+W3iWFJ4iac7z4B0ZI8fxy4R3J956kAI68HclCFGL8MPoUVC3qVA==}
-
resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==}
@@ -6556,10 +6474,6 @@ packages:
resolution: {integrity: sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==}
- resolution: {integrity: sha512-3ZnLvgWF29jikg1sAQ1g0o+lr5JX6sVgYvfUJazn7ZjJroDBUTWp44/+cFVX0bULjv4vci+rBD+oGVAkWqhUbw==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-resvxdc6Mgb7YEThw6G6bExlXKkv6+YbuzGg9xuXxSgxJF7Ozs+o8Y9+2R3sArdWdW8nOokoQb1yrpFB0pQK2g==}
engines: {node: '>=14'}
@@ -6934,10 +6848,6 @@ packages:
resolution: {integrity: sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==}
- resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
- engines: {node: '>= 8'}
-
resolution: {integrity: sha512-c5s35LgVa5tFaHhrZDnr3FpQpjj1BB+RXhLTYUxGqBVN460HkbM8TBtEqdXWbpTKfzwCcjAZVF7zXCYSKtcp9g==}
@@ -7885,52 +7795,15 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@google-cloud/[email protected]':
- dependencies:
- '@google-cloud/common': 6.0.0
- '@google-cloud/paginator': 6.0.0
- '@google-cloud/precise-date': 5.0.0
- '@google-cloud/promisify': 5.0.0
- arrify: 3.0.0
- big.js: 6.2.2
- duplexify: 4.1.3
- extend: 3.0.2
- stream-events: 1.0.5
- teeny-request: 10.1.0
- transitivePeerDependencies:
- - supports-color
-
- '@google-cloud/[email protected]':
- dependencies:
- '@google-cloud/projectify': 4.0.0
- '@google-cloud/promisify': 4.0.0
- arrify: 2.0.1
- duplexify: 4.1.3
- extend: 3.0.2
- google-auth-library: 10.3.0
- html-entities: 2.6.0
- retry-request: 8.0.2
- teeny-request: 10.1.0
- transitivePeerDependencies:
- - supports-color
-
'@google-cloud/[email protected]':
dependencies:
arrify: 2.0.1
extend: 3.0.2
- '@google-cloud/[email protected]':
- dependencies:
- extend: 3.0.2
-
- '@google-cloud/[email protected]': {}
-
'@google-cloud/[email protected]': {}
'@google-cloud/[email protected]': {}
- '@google-cloud/[email protected]': {}
-
dependencies:
'@google-cloud/paginator': 5.0.2
@@ -11946,8 +11819,6 @@ snapshots:
-
@@ -12417,8 +12288,6 @@ snapshots:
-
dependencies:
whatwg-mimetype: 4.0.0
@@ -12847,11 +12716,6 @@ snapshots:
- dependencies:
- node-domexception: 1.0.0
- web-streams-polyfill: 3.3.3
-
@@ -12915,10 +12779,6 @@ snapshots:
dependencies:
fd-package-json: 2.0.0
- dependencies:
- fetch-blob: 3.2.0
-
dependencies:
'@paralleldrive/cuid2': 2.2.2
@@ -12952,14 +12812,6 @@ snapshots:
- encoding
- supports-color
- dependencies:
- extend: 3.0.2
- https-proxy-agent: 7.0.6
- node-fetch: 3.3.2
- transitivePeerDependencies:
- - supports-color
-
dependencies:
gaxios: 6.7.1([email protected])
@@ -12969,14 +12821,6 @@ snapshots:
- encoding
- supports-color
- dependencies:
- gaxios: 7.1.2
- google-logging-utils: 1.1.1
- json-bigint: 1.0.0
- transitivePeerDependencies:
- - supports-color
-
@@ -13054,18 +12898,6 @@ snapshots:
once: 1.4.0
path-is-absolute: 1.0.1
- dependencies:
- base64-js: 1.5.1
- ecdsa-sig-formatter: 1.0.11
- gaxios: 7.1.2
- gcp-metadata: 7.0.1
- google-logging-utils: 1.1.1
- gtoken: 8.0.0
- jws: 4.0.0
- transitivePeerDependencies:
- - supports-color
-
dependencies:
base64-js: 1.5.1
@@ -13080,8 +12912,6 @@ snapshots:
-
dependencies:
get-intrinsic: 1.3.0
@@ -13098,13 +12928,6 @@ snapshots:
- encoding
- supports-color
- dependencies:
- gaxios: 7.1.2
- jws: 4.0.0
- transitivePeerDependencies:
- - supports-color
-
dependencies:
cookie-es: 1.2.2
@@ -14178,8 +14001,6 @@ snapshots:
-
@@ -14190,12 +14011,6 @@ snapshots:
optionalDependencies:
encoding: 0.1.13
- dependencies:
- data-uri-to-buffer: 4.0.1
- fetch-blob: 3.2.0
- formdata-polyfill: 4.0.10
-
dependencies:
detect-libc: 2.1.2
@@ -14614,13 +14429,6 @@ snapshots:
dependencies:
xtend: 4.0.2
- dependencies:
- axios: 1.12.2
- rusha: 0.8.14
- transitivePeerDependencies:
- - debug
-
@@ -14864,13 +14672,6 @@ snapshots:
- encoding
- supports-color
- dependencies:
- extend: 3.0.2
- teeny-request: 10.1.0
- transitivePeerDependencies:
- - supports-color
-
@@ -14898,8 +14699,6 @@ snapshots:
dependencies:
queue-microtask: 1.2.3
-
@@ -15240,15 +15039,6 @@ snapshots:
dependencies:
bintrees: 1.0.2
- dependencies:
- http-proxy-agent: 5.0.0
- https-proxy-agent: 5.0.1
- node-fetch: 3.3.2
- stream-events: 1.0.5
- transitivePeerDependencies:
- - supports-color
-
dependencies:
http-proxy-agent: 5.0.0
@@ -15647,8 +15437,6 @@ snapshots:
dependencies:
makeerror: 1.0.12
-
diff --git a/apps/api/src/__tests__/e2e_noAuth/index.test.ts b/apps/api/src/__tests__/e2e_noAuth/index.test.ts
index 722c1a60d..396521e0b 100644
--- a/apps/api/src/__tests__/e2e_noAuth/index.test.ts
+++ b/apps/api/src/__tests__/e2e_noAuth/index.test.ts
@@ -23,8 +23,6 @@ describe("E2E Tests for API Routes with No Authentication", () => {
process.env.PLAYWRIGHT_MICROSERVICE_URL = "";
process.env.LLAMAPARSE_API_KEY = "";
process.env.TEST_API_KEY = "";
- process.env.POSTHOG_API_KEY = "";
- process.env.POSTHOG_HOST = "";
});
// restore original process.env
diff --git a/apps/api/src/__tests__/job-transform.test.ts b/apps/api/src/__tests__/job-transform.test.ts
deleted file mode 100644
index 5a0e2907d..000000000
--- a/apps/api/src/__tests__/job-transform.test.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { FirecrawlJob } from "../types";
-import { transformJobForLogging, createJobLoggerContext } from "../lib/job-transform";
-
-describe("Job Transformation", () => {
- it("should transform job correctly for database logging", () => {
- const testJob: Partial<FirecrawlJob> = {
- job_id: "test-job-123",
- success: true,
- message: "Test job completed",
- num_docs: 5,
- docs: [{ content: "test content", html: "<p>test</p>" }],
- time_taken: 1500,
- team_id: "test-team",
- mode: "scrape",
- url: "https://example.com",
- crawlerOptions: { maxDepth: 1 },
- scrapeOptions: { includeHtml: true },
- origin: "test-origin",
- num_tokens: 100,
- retry: false,
- tokens_billed: 100,
- };
-
- const transformed = transformJobForLogging(testJob as FirecrawlJob, {
- includeTimestamp: false,
- serializeObjects: false,
- cleanNullValues: true,
- });
-
- expect(transformed).toHaveProperty("job_id", "test-job-123");
- expect(transformed).toHaveProperty("success", true);
- expect(transformed).toHaveProperty("message", "Test job completed");
- expect(transformed).toHaveProperty("num_docs", 5);
- expect(transformed).toHaveProperty("time_taken", 1500);
- expect(transformed).toHaveProperty("team_id", "test-team");
- expect(transformed).toHaveProperty("mode", "scrape");
- expect(transformed).toHaveProperty("url", "https://example.com");
- expect(transformed).toHaveProperty("is_migrated", true);
- expect(transformed).not.toHaveProperty("timestamp");
- expect(typeof transformed.crawler_options).toBe("object");
- expect(typeof transformed.page_options).toBe("object");
- });
-
- it("should transform job correctly for BigQuery logging", () => {
- const testJob: Partial<FirecrawlJob> = {
- job_id: "test-job-123",
- success: true,
- message: "Test job completed",
- num_docs: 5,
- docs: [{ content: "test content", html: "<p>test</p>" }],
- time_taken: 1500,
- team_id: "test-team",
- mode: "scrape",
- url: "https://example.com",
- crawlerOptions: { maxDepth: 1 },
- scrapeOptions: { includeHtml: true },
- origin: "test-origin",
- num_tokens: 100,
- retry: false,
- tokens_billed: 100,
- };
-
- const transformed = transformJobForLogging(testJob as FirecrawlJob, {
- includeTimestamp: true,
- serializeObjects: true,
- cleanNullValues: false,
- });
-
- expect(transformed).toHaveProperty("job_id", "test-job-123");
- expect(transformed).toHaveProperty("success", true);
- expect(transformed).toHaveProperty("timestamp");
- expect(typeof transformed.crawler_options).toBe("string");
- expect(typeof transformed.page_options).toBe("string");
- expect(typeof transformed.docs).toBe("string");
- });
-
- it("should handle zero data retention correctly", () => {
- const testJob: Partial<FirecrawlJob> = {
- job_id: "test-job-zdr",
- success: true,
- message: "Sensitive data",
- url: "https://sensitive.example.com",
- crawlerOptions: { sensitive: "data" },
- scrapeOptions: { headers: { Authorization: "Bearer token" } },
- origin: "sensitive-origin",
- zeroDataRetention: true,
- };
-
- const transformed = transformJobForLogging(testJob as FirecrawlJob);
-
- expect(transformed.message).toBeNull();
- expect(transformed.url).toBe("<redacted due to zero data retention>");
- expect(transformed.crawler_options).toBeNull();
- expect(transformed.page_options).toBeNull();
- expect(transformed.origin).toBeNull();
- expect(transformed.docs).toBeNull();
- });
-
- it("should handle preview team correctly", () => {
- const testJob: Partial<FirecrawlJob> = {
- job_id: "test-job-preview",
- team_id: "preview",
- mode: "scrape",
- };
-
- const transformed = transformJobForLogging(testJob as FirecrawlJob);
- expect(transformed.team_id).toBeNull();
- });
-
- it("should handle preview_ prefixed team correctly", () => {
- const testJob: Partial<FirecrawlJob> = {
- job_id: "test-job-preview-prefixed",
- team_id: "preview_test123",
- mode: "scrape",
- };
-
- const transformed = transformJobForLogging(testJob as FirecrawlJob);
- expect(transformed.team_id).toBeNull();
- });
-
- it("should handle docs exclusion for GCS storage", () => {
- // Set GCS_BUCKET_NAME environment variable
- const originalEnv = process.env.GCS_BUCKET_NAME;
- process.env.GCS_BUCKET_NAME = "test-bucket";
-
- const testJob: Partial<FirecrawlJob> = {
- job_id: "test-job-gcs",
- mode: "scrape",
- docs: [{ content: "test content", html: "<p>test</p>" }],
- };
-
- const transformed = transformJobForLogging(testJob as FirecrawlJob);
- expect(transformed.docs).toBeNull();
-
- // Restore environment
- if (originalEnv) {
- process.env.GCS_BUCKET_NAME = originalEnv;
- } else {
- delete process.env.GCS_BUCKET_NAME;
- }
- });
-
- it("should clean null values when requested", () => {
- const testJob: Partial<FirecrawlJob> = {
- job_id: "test-job-clean",
- docs: [{ content: "test\u0000content", html: "<p>test\u0000</p>" }],
- mode: "scrape",
- };
-
- const transformed = transformJobForLogging(testJob as FirecrawlJob, {
- cleanNullValues: true,
- });
-
- expect(JSON.stringify(transformed.docs)).not.toContain("\\u0000");
- });
-
- describe("Logger Context Creation", () => {
- it("should create correct context for scrape job", () => {
- const job: Partial<FirecrawlJob> = {
- job_id: "scrape-123",
- mode: "scrape",
- };
-
- const context = createJobLoggerContext(job as FirecrawlJob);
- expect(context).toHaveProperty("scrapeId", "scrape-123");
- expect(context).not.toHaveProperty("crawlId");
- expect(context).not.toHaveProperty("extractId");
- });
-
- it("should create correct context for crawl job", () => {
- const job: Partial<FirecrawlJob> = {
- job_id: "crawl-456",
- mode: "crawl",
- };
-
- const context = createJobLoggerContext(job as FirecrawlJob);
- expect(context).toHaveProperty("crawlId", "crawl-456");
- expect(context).not.toHaveProperty("scrapeId");
- expect(context).not.toHaveProperty("extractId");
- });
-
- it("should create correct context for extract job", () => {
- const job: Partial<FirecrawlJob> = {
- job_id: "extract-789",
- mode: "extract",
- };
-
- const context = createJobLoggerContext(job as FirecrawlJob);
- expect(context).toHaveProperty("extractId", "extract-789");
- expect(context).not.toHaveProperty("scrapeId");
- expect(context).not.toHaveProperty("crawlId");
- });
-
- it("should create correct context for single_urls job", () => {
- const job: Partial<FirecrawlJob> = {
- job_id: "single-urls-123",
- mode: "single_urls",
- };
-
- const context = createJobLoggerContext(job as FirecrawlJob);
- expect(context).toHaveProperty("scrapeId", "single-urls-123");
- });
-
- it("should create correct context for batch_scrape job", () => {
- const job: Partial<FirecrawlJob> = {
- job_id: "batch-scrape-456",
- mode: "batch_scrape",
- };
-
- const context = createJobLoggerContext(job as FirecrawlJob);
- expect(context).toHaveProperty("crawlId", "batch-scrape-456");
- });
- });
-});
diff --git a/apps/api/src/__tests__/snips/v1/zdr.test.ts b/apps/api/src/__tests__/snips/v1/zdr.test.ts
index db853250c..4787751d1 100644
--- a/apps/api/src/__tests__/snips/v1/zdr.test.ts
+++ b/apps/api/src/__tests__/snips/v1/zdr.test.ts
@@ -10,9 +10,11 @@ import {
import { describeIf, TEST_PRODUCTION } from "../lib";
import {
getLogs,
- expectJobRecordIsCleanedUp,
- expectJobsArrayIsCleanedUp,
- expectJobsAreFullyCleanedAfterZDRCleaner,
+ expectScrapeIsCleanedUp,
+ expectCrawlIsCleanedUp,
+ expectScrapesOfRequestAreCleanedUp,
+ expectScrapesAreFullyCleanedAfterZDRCleaner,
+ expectBatchScrapeIsCleanedUp,
} from "../zdr-helpers";
describeIf(TEST_PRODUCTION)("Zero Data Retention", () => {
@@ -43,7 +45,7 @@ describeIf(TEST_PRODUCTION)("Zero Data Retention", () => {
const gcsJob = await getJobFromGCS(scrape1.metadata.scrapeId!);
expect(gcsJob).toBeNull();
- await expectJobRecordIsCleanedUp(scrape1.metadata.scrapeId!);
+ await expectScrapeIsCleanedUp(scrape1.metadata.scrapeId!);
if (scope === "Request-scoped") {
const status = await scrapeStatusRaw(
@@ -55,101 +57,115 @@ describeIf(TEST_PRODUCTION)("Zero Data Retention", () => {
}
}, 60000);
- it("should clean up a crawl", async () => {
- const preLogs = await getLogs();
-
- let identity = await idmux({
- name: `zdr/${scope}/crawl`,
- credits: 10000,
- flags: {
- allowZDR: true,
- ...(scope === "Team-scoped"
- ? {
- forceZDR: true,
- }
- : {}),
- },
- });
-
- const crawl1 = await crawl(
- {
- url: "https://firecrawl.dev",
- limit: 10,
- zeroDataRetention: scope === "Request-scoped" ? true : undefined,
- },
- identity,
- );
-
- await new Promise(resolve => setTimeout(resolve, 2500));
+ it(
+ "should clean up a crawl",
+ async () => {
+ const preLogs = await getLogs();
+
+ let identity = await idmux({
+ name: `zdr/${scope}/crawl`,
+ credits: 10000,
+ flags: {
+ allowZDR: true,
+ ...(scope === "Team-scoped"
+ ? {
+ forceZDR: true,
+ }
+ : {}),
+ },
+ });
+
+ const crawl1 = await crawl(
+ {
+ url: "https://firecrawl.dev",
+ limit: 10,
+ zeroDataRetention: scope === "Request-scoped" ? true : undefined,
+ },
+ identity,
+ );
- const postLogs = (await getLogs()).slice(preLogs.length);
+ await new Promise(resolve => setTimeout(resolve, 2500));
- if (postLogs.length > 0) {
- console.warn("Logs changed during crawl", postLogs);
- }
+ const postLogs = (await getLogs()).slice(preLogs.length);
- expect(postLogs).toHaveLength(0);
+ if (postLogs.length > 0) {
+ console.warn("Logs changed during crawl", postLogs);
+ }
- await expectJobRecordIsCleanedUp(crawl1.id);
+ expect(postLogs).toHaveLength(0);
- const jobs = await expectJobsArrayIsCleanedUp(crawl1.id);
+ // wait 20 seconds for crawl finish cron to fire
+ await new Promise(resolve => setTimeout(resolve, 20000));
- await zdrcleaner(identity.teamId!);
+ await expectCrawlIsCleanedUp(crawl1.id);
- await expectJobsAreFullyCleanedAfterZDRCleaner(
- jobs,
- scope,
- identity,
- scrapeStatusRaw,
- );
- }, 600000);
+ const scrapes = await expectScrapesOfRequestAreCleanedUp(crawl1.id);
- it("should clean up a batch scrape", async () => {
- const preLogs = await getLogs();
+ await zdrcleaner(identity.teamId!);
- let identity = await idmux({
- name: `zdr/${scope}/batch-scrape`,
- credits: 10000,
- flags: {
- allowZDR: true,
- ...(scope === "Team-scoped"
- ? {
- forceZDR: true,
- }
- : {}),
- },
- });
+ await expectScrapesAreFullyCleanedAfterZDRCleaner(
+ scrapes,
+ scope,
+ identity,
+ scrapeStatusRaw,
+ );
+ },
+ 600000 + 20000,
+ );
+
+ it(
+ "should clean up a batch scrape",
+ async () => {
+ const preLogs = await getLogs();
+
+ let identity = await idmux({
+ name: `zdr/${scope}/batch-scrape`,
+ credits: 10000,
+ flags: {
+ allowZDR: true,
+ ...(scope === "Team-scoped"
+ ? {
+ forceZDR: true,
+ }
+ : {}),
+ },
+ });
+
+ const crawl1 = await batchScrape(
+ {
+ urls: ["https://firecrawl.dev", "https://mendable.ai"],
+ zeroDataRetention: scope === "Request-scoped" ? true : undefined,
+ },
+ identity,
+ );
- const crawl1 = await batchScrape(
- {
- urls: ["https://firecrawl.dev", "https://mendable.ai"],
- zeroDataRetention: scope === "Request-scoped" ? true : undefined,
- },
- identity,
- );
+ await new Promise(resolve => setTimeout(resolve, 2500));
- await new Promise(resolve => setTimeout(resolve, 2500));
+ const postLogs = (await getLogs()).slice(preLogs.length);
- const postLogs = (await getLogs()).slice(preLogs.length);
+ if (postLogs.length > 0) {
+ console.warn("Logs changed during batch scrape", postLogs);
+ }
- if (postLogs.length > 0) {
- console.warn("Logs changed during batch scrape", postLogs);
- }
+ expect(postLogs).toHaveLength(0);
- expect(postLogs).toHaveLength(0);
+ // wait 20 seconds for batch scrape finish cron to fire
+ await new Promise(resolve => setTimeout(resolve, 20000));
- await expectJobRecordIsCleanedUp(crawl1.id);
+ await expectBatchScrapeIsCleanedUp(crawl1.id);
- const jobs = await expectJobsArrayIsCleanedUp(crawl1.id, 2);
+ const scrapes = await expectScrapesOfRequestAreCleanedUp(crawl1.id, 2);
- await zdrcleaner(identity.teamId!);
+ await zdrcleaner(identity.teamId!);
- await expectJobsAreFullyCleanedAfterZDRCleaner(
- jobs,
- scope,
- identity,
- scrapeStatusRaw,
- );
- }, 600000);
+ await expectScrapesAreFullyCleanedAfterZDRCleaner(
+ scrapes,
+ scope,
+ identity,
+ scrapeStatusRaw,
+ );
+ },
+ 600000 + 20000,
+ );
});
});
diff --git a/apps/api/src/__tests__/snips/v2/zdr.test.ts b/apps/api/src/__tests__/snips/v2/zdr.test.ts
index dcccbe48a..9ed7cce14 100644
--- a/apps/api/src/__tests__/snips/v2/zdr.test.ts
+++ b/apps/api/src/__tests__/snips/v2/zdr.test.ts
@@ -10,9 +10,11 @@ import {
import { describeIf, TEST_PRODUCTION } from "../lib";
import {
getLogs,
- expectJobRecordIsCleanedUp,
- expectJobsArrayIsCleanedUp,
- expectJobsAreFullyCleanedAfterZDRCleaner,
+ expectScrapeIsCleanedUp,
+ expectCrawlIsCleanedUp,
+ expectScrapesOfRequestAreCleanedUp,
+ expectScrapesAreFullyCleanedAfterZDRCleaner,
+ expectBatchScrapeIsCleanedUp,
} from "../zdr-helpers";
describeIf(TEST_PRODUCTION)("Zero Data Retention", () => {
@@ -43,7 +45,7 @@ describeIf(TEST_PRODUCTION)("Zero Data Retention", () => {
const gcsJob = await getJobFromGCS(scrape1.metadata.scrapeId!);
expect(gcsJob).toBeNull();
- await expectJobRecordIsCleanedUp(scrape1.metadata.scrapeId!);
+ await expectScrapeIsCleanedUp(scrape1.metadata.scrapeId!);
if (scope === "Request-scoped") {
const status = await scrapeStatusRaw(
@@ -55,97 +57,110 @@ describeIf(TEST_PRODUCTION)("Zero Data Retention", () => {
}
}, 60000);
- it("should clean up a crawl", async () => {
- const preLogs = await getLogs();
-
- let identity = await idmux({
- name: `zdr/${scope}/crawl`,
- credits: 10000,
- flags: {
- allowZDR: true,
- ...(scope === "Team-scoped"
- ? {
- forceZDR: true,
- }
- : {}),
- },
- });
-
- const crawl1 = await crawl(
- {
- url: "https://firecrawl.dev",
- limit: 10,
- zeroDataRetention: scope === "Request-scoped" ? true : undefined,
- },
- identity,
- );
-
- const postLogs = (await getLogs()).slice(preLogs.length);
-
- if (postLogs.length > 0) {
- console.warn("Logs changed during crawl", postLogs);
- }
+ it(
+ "should clean up a crawl",
+ async () => {
+ const preLogs = await getLogs();
+
+ let identity = await idmux({
+ name: `zdr/${scope}/crawl`,
+ credits: 10000,
+ flags: {
+ allowZDR: true,
+ ...(scope === "Team-scoped"
+ ? {
+ forceZDR: true,
+ }
+ : {}),
+ },
+ });
+
+ const crawl1 = await crawl(
+ {
+ url: "https://firecrawl.dev",
+ limit: 10,
+ zeroDataRetention: scope === "Request-scoped" ? true : undefined,
+ },
+ identity,
+ );
- expect(postLogs).toHaveLength(0);
+ const postLogs = (await getLogs()).slice(preLogs.length);
- await expectJobRecordIsCleanedUp(crawl1.id);
+ if (postLogs.length > 0) {
+ console.warn("Logs changed during crawl", postLogs);
+ }
- const jobs = await expectJobsArrayIsCleanedUp(crawl1.id);
+ expect(postLogs).toHaveLength(0);
- await zdrcleaner(identity.teamId!);
+ // wait 20 seconds for crawl finish cron to fire
+ await new Promise(resolve => setTimeout(resolve, 20000));
- await expectJobsAreFullyCleanedAfterZDRCleaner(
- jobs,
- scope,
- identity,
- scrapeStatusRaw,
- );
- }, 600000);
+ await expectCrawlIsCleanedUp(crawl1.id);
- it("should clean up a batch scrape", async () => {
- const preLogs = await getLogs();
+ const scrapes = await expectScrapesOfRequestAreCleanedUp(crawl1.id);
- let identity = await idmux({
- name: `zdr/${scope}/batch-scrape`,
- credits: 10000,
- flags: {
- allowZDR: true,
- ...(scope === "Team-scoped"
- ? {
- forceZDR: true,
- }
- : {}),
- },
- });
+ await zdrcleaner(identity.teamId!);
- const crawl1 = await batchScrape(
- {
- urls: ["https://firecrawl.dev", "https://mendable.ai"],
- zeroDataRetention: scope === "Request-scoped" ? true : undefined,
- },
- identity,
- );
+ await expectScrapesAreFullyCleanedAfterZDRCleaner(
+ scrapes,
+ scope,
+ identity,
+ scrapeStatusRaw,
+ );
+ },
+ 600000 + 20000,
+ );
+
+ it(
+ "should clean up a batch scrape",
+ async () => {
+ const preLogs = await getLogs();
+
+ let identity = await idmux({
+ name: `zdr/${scope}/batch-scrape`,
+ credits: 10000,
+ flags: {
+ allowZDR: true,
+ ...(scope === "Team-scoped"
+ ? {
+ forceZDR: true,
+ }
+ : {}),
+ },
+ });
+
+ const crawl1 = await batchScrape(
+ {
+ urls: ["https://firecrawl.dev", "https://mendable.ai"],
+ zeroDataRetention: scope === "Request-scoped" ? true : undefined,
+ },
+ identity,
+ );
+ const postLogs = (await getLogs()).slice(preLogs.length);
- const postLogs = (await getLogs()).slice(preLogs.length);
+ if (postLogs.length > 0) {
+ console.warn("Logs changed during batch scrape", postLogs);
+ }
- if (postLogs.length > 0) {
- console.warn("Logs changed during batch scrape", postLogs);
- }
+ expect(postLogs).toHaveLength(0);
- expect(postLogs).toHaveLength(0);
+ // wait 20 seconds for batch scrape finish cron to fire
+ await new Promise(resolve => setTimeout(resolve, 20000));
- await expectJobRecordIsCleanedUp(crawl1.id);
+ await expectBatchScrapeIsCleanedUp(crawl1.id);
- const jobs = await expectJobsArrayIsCleanedUp(crawl1.id, 2);
+ const scrapes = await expectScrapesOfRequestAreCleanedUp(crawl1.id, 2);
- await zdrcleaner(identity.teamId!);
+ await zdrcleaner(identity.teamId!);
- await expectJobsAreFullyCleanedAfterZDRCleaner(
- jobs,
- scope,
- identity,
- scrapeStatusRaw,
- );
- }, 600000);
+ await expectScrapesAreFullyCleanedAfterZDRCleaner(
+ scrapes,
+ scope,
+ identity,
+ scrapeStatusRaw,
+ );
+ },
+ 600000 + 20000,
+ );
});
});
diff --git a/apps/api/src/__tests__/snips/zdr-helpers.ts b/apps/api/src/__tests__/snips/zdr-helpers.ts
index 9e1c18b40..654c1d924 100644
--- a/apps/api/src/__tests__/snips/zdr-helpers.ts
+++ b/apps/api/src/__tests__/snips/zdr-helpers.ts
@@ -33,6 +33,15 @@ export const logIgnoreList = [
"request completed",
"nuqAddJobs metrics",
"nuqGetJobs metrics",
+ "nuqAddGroup metrics",
+ "nuqGetGroup metrics",
+ "NuQ job prefetch sent",
+ "Acquired job",
+ "nuqGetJob metrics",
+ "nuqJobFinish metrics",
+ "Starting to update tallies",
+ "tally for team",
+ "Finished updating tallies",
];
export async function getLogs() {
@@ -76,70 +85,130 @@ export async function getLogs() {
);
}
-export async function expectJobRecordIsCleanedUp(jobId: string) {
- const { data, error } = await supabase_service
- .from("firecrawl_jobs")
+export async function expectScrapeIsCleanedUp(scrapeId: string) {
+ const { data: scrapeData, error: scrapeError } = await supabase_service
+ .from("scrapes")
.select("*")
- .eq("job_id", jobId)
+ .eq("id", scrapeId)
.limit(1);
- expect(error).toBeFalsy();
- expect(data).toHaveLength(1);
+ expect(scrapeError).toBeFalsy();
+ expect(scrapeData).toHaveLength(1);
- if (data && data.length === 1) {
- const record = data[0];
+ if (scrapeData && scrapeData.length === 1) {
+ const record = scrapeData[0];
expect(record.url).not.toContain("://"); // no url stored
- expect(record.docs).toBeNull();
- expect(record.page_options).toBeNull();
- expect(record.crawler_options).toBeNull();
+ expect(record.options).toBeNull();
}
}
-export async function expectJobsArrayIsCleanedUp(
- crawlId: string,
- expectedJobCount?: number,
+export async function expectCrawlIsCleanedUp(crawlId: string) {
+ const { data: requestData, error: requestError } = await supabase_service
+ .from("requests")
+ .select("*")
+ .eq("id", crawlId)
+ .limit(1);
+
+ expect(requestError).toBeFalsy();
+ expect(requestData).toHaveLength(1);
+
+ if (requestData && requestData.length === 1) {
+ const record = requestData[0];
+ expect(record.url).not.toContain("://"); // no url stored
+ expect(record.kind).toBe("crawl");
+ expect(record.dr_clean_by).not.toBeNull();
+ }
+
+ const { data: crawlData, error: crawlError } = await supabase_service
+ .from("crawls")
+ .select("*")
+ .eq("id", crawlId)
+ .limit(1);
+
+ expect(crawlError).toBeFalsy();
+ expect(crawlData).toHaveLength(1);
+
+ if (crawlData && crawlData.length === 1) {
+ const record = crawlData[0];
+ expect(record.url).not.toContain("://"); // no url stored
+ expect(record.options).toBeNull();
+ }
+}
+
+export async function expectBatchScrapeIsCleanedUp(batchScrapeId: string) {
+ const { data: requestData, error: requestError } = await supabase_service
+ .from("requests")
+ .select("*")
+ .eq("id", batchScrapeId)
+ .limit(1);
+
+ expect(requestError).toBeFalsy();
+ expect(requestData).toHaveLength(1);
+
+ if (requestData && requestData.length === 1) {
+ const record = requestData[0];
+ expect(record.url).not.toContain("://"); // no url stored
+ expect(record.kind).toBe("batch_scrape");
+ expect(record.dr_clean_by).not.toBeNull();
+ }
+
+ const { data: batchScrapeData, error: batchScrapeError } = await supabase_service
+ .from("batch_scrapes")
+ .select("*")
+ .eq("id", batchScrapeId)
+ .limit(1);
+
+ expect(batchScrapeError).toBeFalsy();
+ expect(batchScrapeData).toHaveLength(1);
+
+ if (batchScrapeData && batchScrapeData.length === 1) {
+ const record = batchScrapeData[0];
+ expect(record.url).not.toContain("://"); // no url stored
+ }
+}
+
+export async function expectScrapesOfRequestAreCleanedUp(
+ requestId: string,
+ expectedScrapeCount?: number,
) {
- const { data: jobs, error: jobsError } = await supabase_service
- .from("firecrawl_jobs")
+ const { data: scrapes, error: scrapesError } = await supabase_service
+ .from("scrapes")
.select("*")
- .eq("crawl_id", crawlId);
+ .eq("request_id", requestId);
- expect(jobsError).toBeFalsy();
+ expect(scrapesError).toBeFalsy();
- if (expectedJobCount !== undefined) {
- expect((jobs ?? []).length).toBe(expectedJobCount);
+ if (expectedScrapeCount !== undefined) {
+ expect((scrapes ?? []).length).toBe(expectedScrapeCount);
} else {
- expect((jobs ?? []).length).toBeGreaterThanOrEqual(1);
+ expect((scrapes ?? []).length).toBeGreaterThanOrEqual(1);
}
- for (const job of jobs ?? []) {
- expect(job.url).not.toContain("://"); // no url stored
- expect(job.docs).toBeNull();
- expect(job.page_options).toBeNull();
- expect(job.crawler_options).toBeNull();
- expect(typeof job.dr_clean_by).toBe("string"); // clean up happens async on a worker after expiry
+ for (const scrape of scrapes ?? []) {
+ expect(scrape.url).not.toContain("://"); // no url stored
+ expect(scrape.options).toBeNull();
- if (job.success) {
- const gcsJob = await getJobFromGCS(job.job_id);
+ if (scrape.success) {
+ const gcsJob = await getJobFromGCS(scrape.id);
expect(gcsJob).not.toBeNull(); // clean up happens async on a worker after expiry
}
}
- return jobs ?? [];
+ return scrapes ?? [];
}
-export async function expectJobsAreFullyCleanedAfterZDRCleaner(
- jobs: any[],
+export async function expectScrapesAreFullyCleanedAfterZDRCleaner(
+ scrapes: any[],
scope: "Team-scoped" | "Request-scoped",
identity: Identity,
scrapeStatusRaw: ScrapeStatusRawFn,
) {
- for (const job of jobs) {
- const gcsJob = await getJobFromGCS(job.job_id);
+ for (const scrape of scrapes) {
+ const gcsJob = await getJobFromGCS(scrape.id);
expect(gcsJob).toBeNull();
if (scope === "Request-scoped") {
- const status = await scrapeStatusRaw(job.job_id, identity);
+ const status = await scrapeStatusRaw(scrape.id, identity);
expect(status.statusCode).toBe(404);
}
}
diff --git a/apps/api/src/controllers/v0/admin/crawl-check.ts b/apps/api/src/controllers/v0/admin/crawl-check.ts
deleted file mode 100644
index 75b42c5e4..000000000
--- a/apps/api/src/controllers/v0/admin/crawl-check.ts
+++ /dev/null
@@ -1,273 +0,0 @@
-import { Request, Response } from "express";
-import { redisEvictConnection } from "../../../services/redis";
-import {
- getCrawl,
- isCrawlKickoffFinished,
- StoredCrawl,
-} from "../../../lib/crawl-redis";
-import { supabase_service } from "../../../services/supabase";
-import { getConcurrencyLimitedJobs } from "../../../lib/concurrency-limit";
-import { scrapeQueue } from "../../../services/worker/nuq";
-
-type AnalyzedCrawlPass1 = {
- success: true;
- id: string;
- teamId: string;
- crawl: StoredCrawl | null;
- latestJob: any[];
- overarchingJob: any[];
- jobsDoneCount: number;
- jobsCount: number;
- jobsNotDone: Set<string>;
-};
-
-type AnalyzedCrawlPass2 = {
- success: true;
- id: string;
- status:
- | "stuck_other"
- | "stuck_stalled"
- | "stuck_delay"
- | "working"
- | "finished";
- outstandingJobs: string[];
- jobs: {
- total: number;
- done: number;
- pending: number;
- queued: number;
- concurrencyQueued: number;
- outstanding: number;
- };
- kickoffDone: boolean;
- type: "crawl" | "batch_scrape" | "not_sure";
- teamId: string;
-
- createdAt: string;
- updatedAt: string;
-};
-
-type AnalyzedCrawlError = {
- success: false;
- id: string;
- error: string;
-};
-
-async function analyzeCrawlPass1(
- id: string,
-): Promise<AnalyzedCrawlPass1 | AnalyzedCrawlError> {
- const crawl = await getCrawl(id);
-
- if (crawl?.zeroDataRetention) {
- return {
- success: false,
- id,
- error: "Zero Data Retention is enabled for this crawl",
- };
- }
-
- const { data: latestJob, error: latestJobError } = await supabase_service
- .from("firecrawl_jobs")
- .select("*")
- .eq("crawl_id", id)
- .order("date_added", { ascending: false })
- .limit(1);
-
- const { data: overarchingJob, error: overarchingJobError } =
- await supabase_service
- .from("firecrawl_jobs")
- .select("*")
- .eq("job_id", id)
- .limit(1);
-
- if (latestJobError || overarchingJobError) {
- return {
- success: false,
- id,
- error:
- latestJobError?.message ??
- overarchingJobError?.message ??
- "unknown error",
- };
- }
-
- const jobsDoneCount = await redisEvictConnection.scard(
- "crawl:" + id + ":jobs_done",
- );
- const jobsCount = await redisEvictConnection.scard("crawl:" + id + ":jobs");
-
- // job IDs that are not done
- const jobsNotDone = new Set(
- await redisEvictConnection.sdiff(
- "crawl:" + id + ":jobs",
- "crawl:" + id + ":jobs_done",
- ),
- );
-
- return {
- success: true,
- id,
- crawl,
- latestJob,
- overarchingJob,
- jobsDoneCount,
- jobsCount,
- jobsNotDone,
- teamId:
- crawl?.team_id ??
- latestJob[0].team_id ??
- overarchingJob[0].team_id ??
- "unknown",
- };
-}
-
-async function analyzeCrawlPass2(
- {
- id,
- teamId,
- crawl,
- latestJob,
- overarchingJob,
- jobsDoneCount,
- jobsCount,
- jobsNotDone,
- }: AnalyzedCrawlPass1,
- teamConcurrencyQueuedJobs: Set<string>,
-): Promise<AnalyzedCrawlPass2 | AnalyzedCrawlError> {
- const jobsNotDoneNorConcurrencyQueued = new Set(
- [...jobsNotDone].filter(jobId => !teamConcurrencyQueuedJobs.has(jobId)),
- );
-
- const jobsInQueue = await scrapeQueue.getJobs(
- Array.from(jobsNotDoneNorConcurrencyQueued),
- );
-
- const jobsInQueueQueued = new Set(
- jobsInQueue
- .filter(job => job.status === "queued" || job.status === "active")
- .map(job => job.id),
- );
- const jobsInQueueStalled = new Set(
- jobsInQueue
- .filter(job => job.status === "failed" && job.failedReason === null)
- .map(job => job.id),
- );
-
- const jobsNotDoneNorConcurrencyQueuedNorInQueue = new Set(
- [...jobsNotDoneNorConcurrencyQueued].filter(
- jobId => !jobsInQueueQueued.has(jobId),
- ),
- );
-
- return {
- success: true,
- id,
- teamId,
- status: overarchingJob[0]
- ? "finished"
- : jobsNotDoneNorConcurrencyQueuedNorInQueue.size === 0
- ? "working"
- : (
- crawl?.crawlerOptions ??
- overarchingJob[0]?.crawler_options ??
- latestJob[0]?.crawler_options
- )?.delay > 0
- ? "stuck_delay"
- : jobsInQueueStalled.size > 0
- ? "stuck_stalled"
- : "stuck_other",
- kickoffDone: await isCrawlKickoffFinished(id),
- jobs: {
- total: jobsCount,
- done: jobsDoneCount,
- pending: jobsCount - jobsDoneCount,
- queued: jobsInQueueQueued.size,
- concurrencyQueued: [...jobsNotDone].filter(jobId =>
- teamConcurrencyQueuedJobs.has(jobId),
- ).length,
- outstanding: jobsNotDoneNorConcurrencyQueuedNorInQueue.size,
- },
- outstandingJobs: Array.from(jobsNotDoneNorConcurrencyQueuedNorInQueue),
- type: overarchingJob[0]
- ? overarchingJob[0].crawler_options !== null
- ? "crawl"
- : "batch_scrape"
- : latestJob[0]
- ? latestJob[0].crawler_options !== null
- ? "crawl"
- : "batch_scrape"
- : crawl
- ? crawl.crawlerOptions !== null
- ? "crawl"
- : "batch_scrape"
- : "not_sure",
- createdAt: new Date(crawl?.createdAt ?? 0).toISOString(),
- updatedAt: new Date(
- overarchingJob[0]?.date_added ??
- latestJob[0]?.date_added ??
- crawl?.createdAt ??
- 0,
- ).toISOString(),
- };
-}
-
-export async function crawlCheckController(req: Request, res: Response) {
- const activeCrawls = await redisEvictConnection.smembers("active_crawls");
- const firstPass = (
- await Promise.all(activeCrawls.map(analyzeCrawlPass1))
- ).filter(result => result.success);
-
- const teamIds = [...new Set(firstPass.map(result => result.teamId))];
- const teamConcurrencyQueuedJobs = Object.fromEntries(
- await Promise.all(
- teamIds.map(async teamId => [
- teamId,
- await getConcurrencyLimitedJobs(teamId),
- ]),
- ),
- );
-
- const results = await Promise.all(
- firstPass.map(result =>
- analyzeCrawlPass2(
- { ...result },
- teamConcurrencyQueuedJobs[result.teamId],
- ),
- ),
- );
-
- // Clean results which should be "solved"
- const solvedBatchScrapeZeroURLs = results.filter(
- result =>
- result.success &&
- result.type === "batch_scrape" &&
- result.jobs.total === 0,
- );
- // if (solvedBatchScrapeZeroURLs.length > 0) {
- // await redisEvictConnection.srem("active_crawls", solvedBatchScrapeZeroURLs.map(result => result.id));
- // }
-
- res.status(200).json({
- count: results.length,
- perTeam: results.reduce(
- (acc, result) => {
- if (result.success) {
- if (!acc[result.teamId]) {
- acc[result.teamId] = {} as Record<
- AnalyzedCrawlPass2["status"],
- number
- >;
- }
- acc[result.teamId][result.status] =
- (acc[result.teamId][result.status] ?? 0) + 1;
- }
- return acc;
- },
- {} as Record<string, Record<AnalyzedCrawlPass2["status"], number>>,
- ),
- perSymptom: {
- batchScrapeZeroURLs: solvedBatchScrapeZeroURLs.length,
- },
- results,
- });
-}
diff --git a/apps/api/src/controllers/v0/admin/crawl-migration.ts b/apps/api/src/controllers/v0/admin/crawl-migration.ts
new file mode 100644
index 000000000..f30f8eb4a
--- /dev/null
+++ b/apps/api/src/controllers/v0/admin/crawl-migration.ts
@@ -0,0 +1,118 @@
+import { Request, Response } from "express";
+import { redisEvictConnection } from "../../../services/redis";
+import { getCrawl } from "../../../lib/crawl-redis";
+import { supabase_service } from "../../../services/supabase";
+import { logger as _logger } from "../../../lib/logger";
+
+type MigrationResult = {
+ id: string;
+ success: boolean;
+ error?: string;
+ skipped?: boolean;
+};
+
+export async function crawlMigrationController(req: Request, res: Response) {
+ const logger = _logger.child({
+ module: "admin",
+ method: "crawlMigrationController",
+ });
+
+ logger.info("Starting crawl migration...");
+
+ // Get all active crawl IDs from Redis
+ const activeCrawlIds = await redisEvictConnection.smembers("active_crawls");
+
+ logger.info(`Found ${activeCrawlIds.length} active crawls to migrate`);
+
+ const results: MigrationResult[] = [];
+
+ for (const crawlId of activeCrawlIds) {
+ try {
+ // Check if requests entry already exists
+ const { data: existingRequest } = await supabase_service
+ .from("requests")
+ .select("id")
+ .eq("id", crawlId)
+ .single();
+
+ if (existingRequest) {
+ logger.debug(`Crawl ${crawlId} already has a requests entry, skipping`);
+ results.push({ id: crawlId, success: true, skipped: true });
+ continue;
+ }
+
+ // Fetch crawl data from Redis
+ const crawl = await getCrawl(crawlId);
+
+ if (!crawl) {
+ logger.warn(`Crawl ${crawlId} not found in Redis, skipping`);
+ results.push({
+ id: crawlId,
+ success: false,
+ error: "Crawl not found in Redis",
+ });
+ continue;
+ }
+
+ // Determine kind: 'crawl' if crawlerOptions !== null, else 'batch_scrape'
+ const kind = crawl.crawlerOptions !== null ? "crawl" : "batch_scrape";
+
+ // Insert into requests table
+ const { error: insertError } = await supabase_service
+ .from("requests")
+ .insert({
+ id: crawlId,
+ kind: kind,
+ api_version: "legacy",
+ team_id:
+ crawl.team_id === "preview" || crawl.team_id?.startsWith("preview_")
+ ? null
+ : crawl.team_id,
+ origin: "migration",
+ integration: null,
+ target_hint: crawl.zeroDataRetention
+ ? "<redacted due to zero data retention>"
+ : (crawl.originUrl ?? "<unknown>"),
+ dr_clean_by: crawl.zeroDataRetention
+ ? new Date(Date.now() + 24 * 60 * 60 * 1000)
+ : null,
+ });
+
+ if (insertError) {
+ logger.error(`Failed to migrate crawl ${crawlId}`, {
+ error: insertError,
+ });
+ results.push({
+ id: crawlId,
+ success: false,
+ error: insertError.message,
+ });
+ } else {
+ logger.info(`Successfully migrated crawl ${crawlId}`, { kind });
+ results.push({ id: crawlId, success: true });
+ }
+ } catch (error) {
+ logger.error(`Error migrating crawl ${crawlId}`, { error });
+ results.push({
+ id: crawlId,
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ const migrated = results.filter(r => r.success && !r.skipped).length;
+ const skipped = results.filter(r => r.skipped).length;
+ const failed = results.filter(r => !r.success).length;
+
+ logger.info("Crawl migration complete", { migrated, skipped, failed });
+
+ res.status(200).json({
+ success: true,
+ total: activeCrawlIds.length,
+ migrated,
+ skipped,
+ failed,
+ results,
+ });
+}
diff --git a/apps/api/src/controllers/v0/admin/validate-api-key.ts b/apps/api/src/controllers/v0/admin/validate-api-key.ts
index 83d08cc69..1ba170575 100644
--- a/apps/api/src/controllers/v0/admin/validate-api-key.ts
+++ b/apps/api/src/controllers/v0/admin/validate-api-key.ts
@@ -4,6 +4,7 @@ import { supabase_service } from "../../../services/supabase";
import crypto from "crypto";
import { z } from "zod";
import { validate as isUuid } from "uuid";
+import { parseApi } from "../../../lib/parseApi";
export async function integValidateApiKeyController(
req: Request,
@@ -53,7 +54,7 @@ export async function integValidateApiKeyController(
const body = bodySchema.parse(req.body);
- const normalizedApiKey = body.apiKey.replace(/^fc-/, "");
+ const normalizedApiKey = parseApi(body.apiKey);
if (!isUuid(normalizedApiKey)) {
return res.status(400).json({ error: "API key is invalid" });
diff --git a/apps/api/src/controllers/v0/admin/zdrcleaner.ts b/apps/api/src/controllers/v0/admin/zdrcleaner.ts
index 5e68cb9e9..7e1ad206d 100644
--- a/apps/api/src/controllers/v0/admin/zdrcleaner.ts
+++ b/apps/api/src/controllers/v0/admin/zdrcleaner.ts
@@ -9,10 +9,13 @@ async function cleanUpJob(jobId: string) {
await removeJobFromGCS(jobId);
}
-async function cleanUp(specificTeamId: string | null, _logger: Logger) {
+async function cleanUpFirecrawlJobs(
+ specificTeamId: string | null,
+ _logger: Logger,
+) {
const logger = _logger.child({
...(specificTeamId ? { teamId: specificTeamId } : {}),
- method: "cleanUp",
+ method: "cleanUpFirecrawlJobs",
});
const cleanedUp: number[] = [];
@@ -97,13 +100,123 @@ async function cleanUp(specificTeamId: string | null, _logger: Logger) {
}
}
+async function cleanUpRequests(specificTeamId: string | null, _logger: Logger) {
+ const logger = _logger.child({
+ ...(specificTeamId ? { teamId: specificTeamId } : {}),
+ method: "cleanUpRequests",
+ });
+
+ // Track all blobs that need cleanup for each request
+ const requestBlobs = new Map<string, Set<string>>();
+ // Track which blobs were successfully cleaned up
+ const successfulBlobs = new Set<string>();
+
+ try {
+ for (let i = 0; ; i++) {
+ // Call the RPC to get all blobs (scrapes, searches, extracts, maps, llmstxts, deep_researches)
+ // associated with requests that need cleanup.
+ // The RPC handles the dr_clean_by filtering logic (team-specific vs scheduled)
+ const { data: rows, error } = await supabase_service.rpc(
+ "get_zdr_cleanup_batch",
+ {
+ p_team_id: specificTeamId,
+ p_limit: 1000,
+ p_offset: i * 1000,
+ },
+ );
+
+ if (error) {
+ logger.error("Error calling get_zdr_cleanup_batch RPC", { error });
+ throw error;
+ }
+
+ if (!rows || rows.length === 0) {
+ break;
+ }
+
+ // Track all blobs for each request before processing
+ for (const row of rows as { request_id: string; blob_id: string }[]) {
+ if (!requestBlobs.has(row.request_id)) {
+ requestBlobs.set(row.request_id, new Set());
+ }
+ requestBlobs.get(row.request_id)!.add(row.blob_id);
+ }
+
+ // Process in batches of 50 for GCS cleanup
+ for (let j = 0; j < Math.ceil(rows.length / 50); j++) {
+ const batch = rows.slice(j * 50, (j + 1) * 50);
+ await Promise.allSettled(
+ batch.map(async (row: { request_id: string; blob_id: string }) => {
+ try {
+ await cleanUpJob(row.blob_id);
+ successfulBlobs.add(row.blob_id);
+ } catch (error) {
+ logger.error(`Error cleaning up blob`, {
+ method: "cleanUpJob",
+ blobId: row.blob_id,
+ requestId: row.request_id,
+ error,
+ });
+ // Don't throw - continue with other blobs
+ }
+ }),
+ );
+ }
+
+ if (rows.length < 1000) {
+ break;
+ }
+ }
+ } catch (error) {
+ logger.error(`Error looping through cleanup batch`, {
+ error,
+ });
+ }
+
+ // Only clear dr_clean_by on requests where ALL blobs were successfully cleaned up
+ const fullyCleanedRequests: string[] = [];
+ for (const [requestId, blobIds] of requestBlobs) {
+ const allBlobsCleaned = [...blobIds].every(blobId =>
+ successfulBlobs.has(blobId),
+ );
+ if (allBlobsCleaned) {
+ fullyCleanedRequests.push(requestId);
+ }
+ }
+
+ if (fullyCleanedRequests.length > 0) {
+ try {
+ await supabase_service
+ .from("requests")
+ .update({
+ dr_clean_by: null,
+ })
+ .in("id", fullyCleanedRequests)
+ .throwOnError();
+
+ logger.info(`Cleaned up ${fullyCleanedRequests.length} requests`);
+ } catch (error) {
+ logger.error(`Error clearing dr_clean_by on requests`, {
+ error,
+ requestCount: fullyCleanedRequests.length,
+ });
+ }
+ }
+}
+
export async function zdrcleanerController(req: Request, res: Response) {
const logger = _logger.child({
module: "zdrcleaner",
method: "zdrcleanerController",
});
- await cleanUp((req.query.teamId as string | undefined) ?? null, logger);
+ const teamId = (req.query.teamId as string | undefined) ?? null;
+
+ // Clean up old firecrawl_jobs table (legacy)
+ await cleanUpFirecrawlJobs(teamId, logger);
+
+ // Clean up new requests/scrapes tables
+ await cleanUpRequests(teamId, logger);
logger.info("ZDR Cleaner finished!");
diff --git a/apps/api/src/controllers/v0/crawl-status.ts b/apps/api/src/controllers/v0/crawl-status.ts
index 5a17c08c8..048a56a8d 100644
--- a/apps/api/src/controllers/v0/crawl-status.ts
+++ b/apps/api/src/controllers/v0/crawl-status.ts
@@ -4,11 +4,11 @@ import { RateLimiterMode } from "../../../src/types";
import { redisEvictConnection } from "../../../src/services/redis";
import { logger } from "../../../src/lib/logger";
import { getCrawl, getCrawlJobs } from "../../../src/lib/crawl-redis";
-import { supabaseGetJobsByCrawlId } from "../../../src/lib/supabase-jobs";
+import { supabaseGetScrapesByRequestId } from "../../../src/lib/supabase-jobs";
import * as Sentry from "@sentry/node";
import { configDotenv } from "dotenv";
import { toLegacyDocument } from "../v1/types";
-import type { DBJob, PseudoJob } from "../v1/crawl-status";
+import type { DBScrape, PseudoJob } from "../v1/crawl-status";
import { getJobFromGCS } from "../../lib/gcs-jobs";
import { scrapeQueue, NuQJob } from "../../services/worker/nuq";
configDotenv();
@@ -17,10 +17,10 @@ async function getJobs(
crawlId: string,
ids: string[],
): Promise<PseudoJob<any>[]> {
- const [nuqJobs, dbJobs, gcsJobs] = await Promise.all([
+ const [nuqJobs, dbScrapes, gcsJobs] = await Promise.all([
scrapeQueue.getJobs(ids),
process.env.USE_DB_AUTHENTICATION === "true"
- ? await supabaseGetJobsByCrawlId(crawlId)
+ ? await supabaseGetScrapesByRequestId(crawlId)
: [],
process.env.GCS_BUCKET_NAME
? (Promise.all(
@@ -32,15 +32,15 @@ async function getJobs(
]);
const nuqJobMap = new Map<string, NuQJob<any, any>>();
- const dbJobMap = new Map<string, DBJob>();
+ const dbScrapeMap = new Map<string, DBScrape>();
const gcsJobMap = new Map<string, any>();
for (const job of nuqJobs) {
nuqJobMap.set(job.id, job);
}
- for (const job of dbJobs) {
- dbJobMap.set(job.job_id, job);
+ for (const scrape of dbScrapes) {
+ dbScrapeMap.set(scrape.id, scrape);
}
for (const job of gcsJobs) {
@@ -51,12 +51,12 @@ async function getJobs(
for (const id of ids) {
const nuqJob = nuqJobMap.get(id);
- const dbJob = dbJobMap.get(id);
+ const dbScrape = dbScrapeMap.get(id);
const gcsJob = gcsJobMap.get(id);
- if (!nuqJob && !dbJob) continue;
+ if (!nuqJob && !dbScrape) continue;
- const data = gcsJob ?? dbJob?.docs ?? nuqJob?.returnvalue;
+ const data = gcsJob ?? nuqJob?.returnvalue;
if (gcsJob === null && data) {
logger.warn("GCS Job not found", {
jobId: id,
@@ -65,16 +65,20 @@ async function getJobs(
const job: PseudoJob<any> = {
id,
- status: dbJob ? (dbJob.success ? "completed" : "failed") : nuqJob!.status,
+ status: dbScrape
+ ? dbScrape.success
+ ? "completed"
+ : "failed"
+ : nuqJob!.status,
returnvalue: Array.isArray(data) ? data[0] : data,
data: {
- scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbJob!.page_options,
+ scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbScrape!.options,
},
timestamp: nuqJob
? nuqJob.createdAt.valueOf()
- : new Date(dbJob!.date_added).valueOf(),
+ : new Date(dbScrape!.created_at).valueOf(),
failedReason:
- (nuqJob ? nuqJob.failedReason : dbJob!.message) || undefined,
+ (nuqJob ? nuqJob.failedReason : dbScrape!.error) || undefined,
};
jobs.push(job);
diff --git a/apps/api/src/controllers/v0/crawl.ts b/apps/api/src/controllers/v0/crawl.ts
index 6e21c5e97..a20ea9235 100644
--- a/apps/api/src/controllers/v0/crawl.ts
+++ b/apps/api/src/controllers/v0/crawl.ts
@@ -34,6 +34,7 @@ import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";
import { fromV0ScrapeOptions } from "../v2/types";
import { isSelfHosted } from "../../lib/deployment";
import { crawlGroup } from "../../services/worker/nuq";
+import { logRequest } from "../../services/logging/log_job";
export async function crawlController(req: Request, res: Response) {
try {
@@ -53,6 +54,17 @@ export async function crawlController(req: Request, res: Response) {
const id = uuidv7();
+ await logRequest({
+ id,
+ kind: "crawl",
+ api_version: "v0",
+ team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.url ?? "",
+ zeroDataRetention: false, // not supported on v0
+ });
+
redisEvictConnection.sadd("teams_using_v0", team_id).catch(error =>
logger.error("Failed to add team to teams_using_v0", {
error,
diff --git a/apps/api/src/controllers/v0/scrape.ts b/apps/api/src/controllers/v0/scrape.ts
index 267054bb1..4a9e91d41 100644
--- a/apps/api/src/controllers/v0/scrape.ts
+++ b/apps/api/src/controllers/v0/scrape.ts
@@ -24,6 +24,7 @@ import { fromV0Combo } from "../v2/types";
import { ScrapeJobTimeoutError } from "../../lib/error";
import { scrapeQueue } from "../../services/worker/nuq";
import { getErrorContactMessage } from "../../lib/deployment";
+import { logRequest } from "../../services/logging/log_job";
async function scrapeHelper(
jobId: string,
@@ -178,6 +179,17 @@ export async function scrapeController(req: Request, res: Response) {
const jobId = uuidv7();
+ await logRequest({
+ id: jobId,
+ kind: "scrape",
+ api_version: "v0",
+ team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.url ?? "",
+ zeroDataRetention: false, // not supported on v0
+ });
+
redisEvictConnection.sadd("teams_using_v0", team_id).catch(error =>
logger.error("Failed to add team to teams_using_v0", {
error,
diff --git a/apps/api/src/controllers/v0/search.ts b/apps/api/src/controllers/v0/search.ts
index 9a9722748..f9e81fe27 100644
--- a/apps/api/src/controllers/v0/search.ts
+++ b/apps/api/src/controllers/v0/search.ts
@@ -5,7 +5,7 @@ import {
} from "../../services/billing/credit_billing";
import { authenticateUser } from "../auth";
import { RateLimiterMode, ScrapeJobSingleUrls } from "../../types";
-import { logJob } from "../../services/logging/log_job";
+import { logSearch, logRequest } from "../../services/logging/log_job";
import { PageOptions, SearchOptions } from "../../lib/entities";
import { search } from "../../search";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
@@ -119,6 +119,7 @@ async function searchHelper(
zeroDataRetention: false, // not supported on v0
apiKeyId: api_key_id,
origin: req.body.origin ?? defaultOrigin,
+ requestId: jobId,
} satisfies ScrapeJobSingleUrls,
};
});
@@ -177,6 +178,17 @@ export async function searchController(req: Request, res: Response) {
const jobId = uuidv7();
+ await logRequest({
+ id: jobId,
+ kind: "search",
+ api_version: "v0",
+ team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.query ?? "",
+ zeroDataRetention: false, // not supported on v0
+ });
+
redisEvictConnection.sadd("teams_using_v0", team_id).catch(error =>
logger.error("Failed to add team to teams_using_v0", {
error,
@@ -230,25 +242,20 @@ export async function searchController(req: Request, res: Response) {
);
const endTime = new Date().getTime();
const timeTakenInSeconds = (endTime - startTime) / 1000;
- logJob({
- job_id: jobId,
- success: result.success,
- message: result.error,
- num_docs: result.data ? result.data.length : 0,
- docs: result.data,
+ await logSearch({
+ id: jobId,
+ request_id: jobId,
+ query: req.body.query,
+ num_results: result.data?.length ?? 0,
+ is_successful: result.success,
+ error: result.error,
+ results: result.data,
time_taken: timeTakenInSeconds,
team_id: team_id,
- mode: "search",
- url: req.body.query,
- scrapeOptions: fromLegacyScrapeOptions(
- req.body.pageOptions,
- undefined,
- 60000,
- team_id,
- ),
- crawlerOptions: crawlerOptions,
- origin,
- integration: req.body.integration,
+ options: searchOptions,
+ credits_cost: pageOptions.fetchPageContent
+ ? 0
+ : (result.data?.length ?? 0),
zeroDataRetention: false, // not supported
});
return res.status(result.returnCode).json(result);
diff --git a/apps/api/src/controllers/v1/__tests__/crawl.test.ts.WIP b/apps/api/src/controllers/v1/__tests__/crawl.test.ts.WIP
deleted file mode 100644
index 6db51ff27..000000000
--- a/apps/api/src/controllers/v1/__tests__/crawl.test.ts.WIP
+++ /dev/null
@@ -1,47 +0,0 @@
-import { crawlController } from '../crawl'
-import { Request, Response } from 'express';
-import { authenticateUser } from '../auth'; // Ensure this import is correct
-import { createIdempotencyKey } from '../../services/idempotency/create';
-import { validateIdempotencyKey } from '../../services/idempotency/validate';
-import { v7 as uuidv7 } from 'uuid';
-
-jest.mock('../auth', () => ({
- authenticateUser: jest.fn().mockResolvedValue({
- success: true,
- team_id: 'team123',
- error: null,
- status: 200
- }),
- reduce: jest.fn()
-}));
-jest.mock('../../services/idempotency/validate');
-
-describe('crawlController', () => {
- it('should prevent duplicate requests using the same idempotency key', async () => {
- const req = {
- headers: {
- 'x-idempotency-key': await uuidv7(),
- 'Authorization': `Bearer ${process.env.TEST_API_KEY}`
- },
- body: {
- url: 'https://mendable.ai'
- }
- } as unknown as Request;
- const res = {
- status: jest.fn().mockReturnThis(),
- json: jest.fn()
- } as unknown as Response;
-
- // Mock the idempotency key validation to return false for the second call
- (validateIdempotencyKey as jest.Mock).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
-
- // First request should succeed
- await crawlController(req, res);
- expect(res.status).not.toHaveBeenCalledWith(409);
-
- // Second request with the same key should fail
- await crawlController(req, res);
- expect(res.status).toHaveBeenCalledWith(409);
- expect(res.json).toHaveBeenCalledWith({ error: 'Idempotency key already used' });
- });
-});
\ No newline at end of file
diff --git a/apps/api/src/controllers/v1/batch-scrape.ts b/apps/api/src/controllers/v1/batch-scrape.ts
index cf31a4d6f..c6936e068 100644
--- a/apps/api/src/controllers/v1/batch-scrape.ts
+++ b/apps/api/src/controllers/v1/batch-scrape.ts
@@ -26,6 +26,7 @@ import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import { fromV1ScrapeOptions } from "../v2/types";
import { checkPermissions } from "../../lib/permissions";
import { crawlGroup } from "../../services/worker/nuq";
+import { logRequest } from "../../services/logging/log_job";
export async function batchScrapeController(
req: RequestWithAuth<{}, BatchScrapeResponse, BatchScrapeRequest>,
@@ -110,6 +111,19 @@ export async function batchScrapeController(
account: req.account,
});
+ if (!req.body.appendToId) {
+ await logRequest({
+ id,
+ kind: "batch_scrape",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: urls[0] ?? "",
+ zeroDataRetention: zeroDataRetention || false,
+ });
+ }
+
const { scrapeOptions, internalOptions } = fromV1ScrapeOptions(
req.body,
req.body.timeout,
diff --git a/apps/api/src/controllers/v1/crawl-errors.ts b/apps/api/src/controllers/v1/crawl-errors.ts
index f0899c616..55e1ad837 100644
--- a/apps/api/src/controllers/v1/crawl-errors.ts
+++ b/apps/api/src/controllers/v1/crawl-errors.ts
@@ -73,21 +73,22 @@ export async function crawlErrorsController(
),
});
} else if (process.env.USE_DB_AUTHENTICATION === "true") {
- const { data: crawlJobs, error: crawlJobError } = await supabase_rr_service
- .from("firecrawl_jobs")
+ // Check the requests table for the crawl/batch scrape request
+ const { data: request, error: requestError } = await supabase_rr_service
+ .from("requests")
.select("*")
- .eq("job_id", req.params.jobId)
+ .eq("id", req.params.jobId)
.limit(1)
.throwOnError();
- if (crawlJobError) {
- _logger.error("Error getting crawl job", { error: crawlJobError });
- throw crawlJobError;
+ if (requestError) {
+ _logger.error("Error getting request", { error: requestError });
+ throw requestError;
}
- const crawlJob = crawlJobs[0];
+ const requestData = request?.[0];
- if (crawlJob && crawlJob.team_id !== req.auth.team_id) {
+ if (requestData && requestData.team_id !== req.auth.team_id) {
return res.status(403).json({ success: false, error: "Forbidden" });
}
@@ -95,50 +96,53 @@ export async function crawlErrorsController(
const crawlTtlMs = crawlTtlHours * 60 * 60 * 1000;
if (
- crawlJob &&
- new Date().valueOf() - new Date(crawlJob.date_added).valueOf() >
+ requestData &&
+ new Date().valueOf() - new Date(requestData.created_at).valueOf() >
crawlTtlMs
) {
return res.status(404).json({ success: false, error: "Job expired" });
}
- if (!crawlJobs || crawlJobs.length === 0) {
+ if (!request || request.length === 0) {
return res.status(404).json({ success: false, error: "Job not found" });
}
- const { data: failedJobs, error: failedJobsError } =
+ // Get failed scrapes from the scrapes table
+ const { data: failedScrapes, error: failedScrapesError } =
await supabase_rr_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select("*")
- .eq("crawl_id", req.params.jobId)
+ .eq("request_id", req.params.jobId)
.eq("team_id", req.auth.team_id)
.eq("success", false)
.throwOnError();
- if (failedJobsError) {
- _logger.error("Error getting failed jobs", { error: failedJobsError });
- throw failedJobsError;
+ if (failedScrapesError) {
+ _logger.error("Error getting failed scrapes", {
+ error: failedScrapesError,
+ });
+ throw failedScrapesError;
}
res.status(200).json({
- errors: (failedJobs || []).map(job => {
+ errors: (failedScrapes || []).map(scrape => {
const error = deserializeTransportableError(
- job.message,
+ scrape.error,
) as TransportableError | null;
return {
- id: job.job_id,
+ id: scrape.id,
timestamp:
- job.finishedOn !== undefined
- ? new Date(job.finishedOn).toISOString()
+ scrape.created_at !== undefined
+ ? new Date(scrape.created_at).toISOString()
: undefined,
- url: job.url,
+ url: scrape.url,
...(error
? {
code: error.code,
error: error.message,
}
: {
- error: job.message,
+ error: scrape.error,
}),
};
}),
diff --git a/apps/api/src/controllers/v1/crawl-status.ts b/apps/api/src/controllers/v1/crawl-status.ts
index 42a0ebc2e..82eaddc9d 100644
--- a/apps/api/src/controllers/v1/crawl-status.ts
+++ b/apps/api/src/controllers/v1/crawl-status.ts
@@ -14,8 +14,8 @@ import {
getDoneJobsOrderedUntil,
} from "../../lib/crawl-redis";
import {
- supabaseGetJobById,
- supabaseGetJobsById,
+ supabaseGetScrapeById,
+ supabaseGetScrapesById,
} from "../../lib/supabase-jobs";
import { configDotenv } from "dotenv";
import { logger } from "../../lib/logger";
@@ -42,33 +42,33 @@ export type PseudoJob<T> = {
failedReason?: string;
};
-export type DBJob = {
- docs: any;
+export type DBScrape = {
+ id: string;
success: boolean;
- page_options: any;
- date_added: any;
- message: string | null;
+ options: any;
+ created_at: any;
+ error: string | null;
team_id: string;
};
export async function getJob(id: string): Promise<PseudoJob<any> | null> {
- const [nuqJob, dbJob, gcsJob] = await Promise.all([
+ const [nuqJob, dbScrape, gcsJob] = await Promise.all([
scrapeQueue.getJob(id) as Promise<NuQJob<ScrapeJobSingleUrls> | null>,
(process.env.USE_DB_AUTHENTICATION === "true"
- ? supabaseGetJobById(id)
- : null) as Promise<DBJob | null>,
+ ? supabaseGetScrapeById(id)
+ : null) as Promise<DBScrape | null>,
(process.env.GCS_BUCKET_NAME ? getJobFromGCS(id) : null) as Promise<
any | null
>,
]);
- if (!nuqJob && !dbJob) return null;
+ if (!nuqJob && !dbScrape) return null;
if (nuqJob && nuqJob.data.mode !== "single_urls") {
return null;
}
- const data = gcsJob ?? dbJob?.docs ?? nuqJob?.returnvalue;
+ const data = gcsJob ?? nuqJob?.returnvalue;
if (gcsJob === null && data) {
logger.warn("GCS Job not found", {
jobId: id,
@@ -77,25 +77,29 @@ export async function getJob(id: string): Promise<PseudoJob<any> | null> {
const job: PseudoJob<any> = {
id,
- status: dbJob ? (dbJob.success ? "completed" : "failed") : nuqJob!.status,
+ status: dbScrape
+ ? dbScrape.success
+ ? "completed"
+ : "failed"
+ : nuqJob!.status,
returnvalue: Array.isArray(data) ? data[0] : data,
data: {
- scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbJob!.page_options,
+ scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbScrape!.options,
},
timestamp: nuqJob
? nuqJob.createdAt.valueOf()
- : new Date(dbJob!.date_added).valueOf(),
- failedReason: (nuqJob ? nuqJob.failedReason : dbJob!.message) || undefined,
+ : new Date(dbScrape!.created_at).valueOf(),
+ failedReason: (nuqJob ? nuqJob.failedReason : dbScrape!.error) || undefined,
};
return job;
}
export async function getJobs(ids: string[]): Promise<PseudoJob<any>[]> {
- const [nuqJobs, dbJobs, gcsJobs] = await Promise.all([
+ const [nuqJobs, dbScrapes, gcsJobs] = await Promise.all([
scrapeQueue.getJobs(ids) as Promise<NuQJob<ScrapeJobSingleUrls>[]>,
process.env.USE_DB_AUTHENTICATION === "true"
- ? supabaseGetJobsById(ids)
+ ? supabaseGetScrapesById(ids)
: [],
process.env.GCS_BUCKET_NAME
? (Promise.all(
@@ -107,15 +111,15 @@ export async function getJobs(ids: string[]): Promise<PseudoJob<any>[]> {
]);
const nuqJobMap = new Map<string, NuQJob<any, any>>();
- const dbJobMap = new Map<string, DBJob>();
+ const dbScrapeMap = new Map<string, DBScrape>();
const gcsJobMap = new Map<string, any>();
for (const job of nuqJobs) {
nuqJobMap.set(job.id, job);
}
- for (const job of dbJobs) {
- dbJobMap.set(job.job_id, job);
+ for (const scrape of dbScrapes) {
+ dbScrapeMap.set(scrape.id, scrape);
}
for (const job of gcsJobs) {
@@ -126,12 +130,12 @@ export async function getJobs(ids: string[]): Promise<PseudoJob<any>[]> {
for (const id of ids) {
const nuqJob = nuqJobMap.get(id);
- const dbJob = dbJobMap.get(id);
+ const dbScrape = dbScrapeMap.get(id);
const gcsJob = gcsJobMap.get(id);
- if (!nuqJob && !dbJob) continue;
+ if (!nuqJob && !dbScrape) continue;
- const data = gcsJob ?? dbJob?.docs ?? nuqJob?.returnvalue;
+ const data = gcsJob ?? nuqJob?.returnvalue;
if (gcsJob === null && data) {
logger.warn("GCS Job not found", {
jobId: id,
@@ -140,16 +144,20 @@ export async function getJobs(ids: string[]): Promise<PseudoJob<any>[]> {
const job: PseudoJob<any> = {
id,
- status: dbJob ? (dbJob.success ? "completed" : "failed") : nuqJob!.status,
+ status: dbScrape
+ ? dbScrape.success
+ ? "completed"
+ : "failed"
+ : nuqJob!.status,
returnvalue: Array.isArray(data) ? data[0] : data,
data: {
- scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbJob!.page_options,
+ scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbScrape!.options,
},
timestamp: nuqJob
? nuqJob.createdAt.valueOf()
- : new Date(dbJob!.date_added).valueOf(),
+ : new Date(dbScrape!.created_at).valueOf(),
failedReason:
- (nuqJob ? nuqJob.failedReason : dbJob!.message) || undefined,
+ (nuqJob ? nuqJob.failedReason : dbScrape!.error) || undefined,
};
jobs.push(job);
@@ -193,7 +201,7 @@ export async function crawlStatusController(
const creditsRpc =
process.env.USE_DB_AUTHENTICATION === "true"
? await supabase_service.rpc(
- "credits_billed_by_crawl_id_1",
+ "credits_billed_by_crawl_id_2",
{
i_crawl_id: req.params.jobId,
},
diff --git a/apps/api/src/controllers/v1/crawl.ts b/apps/api/src/controllers/v1/crawl.ts
index 6ab3407d2..39df4b6cd 100644
--- a/apps/api/src/controllers/v1/crawl.ts
+++ b/apps/api/src/controllers/v1/crawl.ts
@@ -18,6 +18,7 @@ import { logger as _logger } from "../../lib/logger";
import { fromV1ScrapeOptions } from "../v2/types";
import { checkPermissions } from "../../lib/permissions";
import { crawlGroup } from "../../services/worker/nuq";
+import { logRequest } from "../../services/logging/log_job";
export async function crawlController(
req: RequestWithAuth<{}, CrawlResponse, CrawlRequest>,
@@ -52,6 +53,17 @@ export async function crawlController(
account: req.account,
});
+ await logRequest({
+ id,
+ kind: "crawl",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.url,
+ zeroDataRetention: zeroDataRetention || false,
+ });
+
let { remainingCredits } = req.account!;
const useDbAuthentication = process.env.USE_DB_AUTHENTICATION === "true";
if (!useDbAuthentication) {
@@ -162,7 +174,7 @@ export async function crawlController(
zeroDataRetention: zeroDataRetention || false,
apiKeyId: req.acuc?.api_key_id ?? null,
},
- crypto.randomUUID(),
+ uuidv7(),
);
const protocol = req.protocol;
diff --git a/apps/api/src/controllers/v1/deep-research-status.ts b/apps/api/src/controllers/v1/deep-research-status.ts
index b261e7be3..cff1d9500 100644
--- a/apps/api/src/controllers/v1/deep-research-status.ts
+++ b/apps/api/src/controllers/v1/deep-research-status.ts
@@ -4,7 +4,6 @@ import {
getDeepResearch,
getDeepResearchExpiry,
} from "../../lib/deep-research/deep-research-redis";
-import { supabaseGetJobsById } from "../../lib/supabase-jobs";
export async function deepResearchStatusController(
req: RequestWithAuth<{ jobId: string }, any, any>,
@@ -19,18 +18,6 @@ export async function deepResearchStatusController(
});
}
- let data: any = null;
-
- if (
- research.status === "completed" &&
- process.env.USE_DB_AUTHENTICATION === "true"
- ) {
- const jobData = await supabaseGetJobsById([req.params.jobId]);
- if (jobData && jobData.length > 0) {
- data = jobData[0].docs[0];
- }
- }
-
return res.status(200).json({
success: research.status === "failed" ? false : true,
data: {
diff --git a/apps/api/src/controllers/v1/deep-research.ts b/apps/api/src/controllers/v1/deep-research.ts
index 086d6f655..36be68608 100644
--- a/apps/api/src/controllers/v1/deep-research.ts
+++ b/apps/api/src/controllers/v1/deep-research.ts
@@ -5,6 +5,7 @@ import { getDeepResearchQueue } from "../../services/queue-service";
import * as Sentry from "@sentry/node";
import { saveDeepResearch } from "../../lib/deep-research/deep-research-redis";
import { z } from "zod";
+import { logRequest } from "../../services/logging/log_job";
const deepResearchRequestSchema = z
.object({
@@ -91,6 +92,17 @@ export async function deepResearchController(
req.body = deepResearchRequestSchema.parse(req.body);
const researchId = uuidv7();
+
+ await logRequest({
+ id: researchId,
+ kind: "deep_research",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: "api",
+ target_hint: req.body.query ?? "",
+ zeroDataRetention: false, // not supported for deep research
+ });
+
const jobData = {
request: req.body,
teamId: req.auth.team_id,
diff --git a/apps/api/src/controllers/v1/extract-status.ts b/apps/api/src/controllers/v1/extract-status.ts
index 95f33446c..3e7a80183 100644
--- a/apps/api/src/controllers/v1/extract-status.ts
+++ b/apps/api/src/controllers/v1/extract-status.ts
@@ -1,13 +1,21 @@
import { Response } from "express";
import { RequestWithAuth } from "./types";
import { getExtract, getExtractExpiry } from "../../lib/extract/extract-redis";
-import { DBJob } from "./crawl-status";
import { getExtractQueue } from "../../services/queue-service";
import { ExtractResult } from "../../lib/extract/extraction-service";
-import { supabaseGetJobByIdDirect } from "../../lib/supabase-jobs";
+import { supabaseGetExtractByIdDirect } from "../../lib/supabase-jobs";
import { JobState } from "bullmq";
import { logger as _logger } from "../../lib/logger";
+type DBExtract = {
+ id: string;
+ success: boolean;
+ options: any;
+ created_at: any;
+ error: string | null;
+ team_id: string;
+};
+
type ExtractPseudoJob<T> = {
id: string;
getState: () => Promise<JobState | "unknown"> | JobState | "unknown";
@@ -23,32 +31,33 @@ type ExtractPseudoJob<T> = {
async function getExtractJob(
id: string,
): Promise<ExtractPseudoJob<ExtractResult> | null> {
- const [bullJob, dbJob] = await Promise.all([
+ const [bullJob, dbExtract] = await Promise.all([
getExtractQueue().getJob(id),
(process.env.USE_DB_AUTHENTICATION === "true"
- ? supabaseGetJobByIdDirect(id)
- : null) as Promise<DBJob | null>,
+ ? supabaseGetExtractByIdDirect(id)
+ : null) as Promise<DBExtract | null>,
]);
- if (!bullJob && !dbJob) return null;
+ if (!bullJob && !dbExtract) return null;
- const data = dbJob?.docs ?? bullJob?.returnvalue?.data;
+ // Extract results are stored in GCS, not in the DB
+ const data = bullJob?.returnvalue?.data;
const job: ExtractPseudoJob<any> = {
id,
- getState: dbJob
- ? () => (dbJob.success ? "completed" : "failed")
+ getState: dbExtract
+ ? () => (dbExtract.success ? "completed" : "failed")
: () => bullJob!.getState(),
returnvalue: data,
data: {
- scrapeOptions: bullJob ? bullJob.data.scrapeOptions : dbJob!.page_options,
- teamId: bullJob ? bullJob.data.teamId : dbJob!.team_id,
+ scrapeOptions: bullJob ? bullJob.data.scrapeOptions : dbExtract!.options,
+ teamId: bullJob ? bullJob.data.teamId : dbExtract!.team_id,
},
timestamp: bullJob
? bullJob.timestamp
- : new Date(dbJob!.date_added).valueOf(),
+ : new Date(dbExtract!.created_at).valueOf(),
failedReason:
- (bullJob ? bullJob.failedReason : dbJob!.message) || undefined,
+ (bullJob ? bullJob.failedReason : dbExtract!.error) || undefined,
};
return job;
diff --git a/apps/api/src/controllers/v1/extract.ts b/apps/api/src/controllers/v1/extract.ts
index fb4ba20e1..798ac4b89 100644
--- a/apps/api/src/controllers/v1/extract.ts
+++ b/apps/api/src/controllers/v1/extract.ts
@@ -19,6 +19,7 @@ import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import { logger as _logger } from "../../lib/logger";
import { fromV1ScrapeOptions } from "../v2/types";
import { createWebhookSender, WebhookEvent } from "../../services/webhook";
+import { logRequest } from "../../services/logging/log_job";
async function oldExtract(
req: RequestWithAuth<{}, ExtractResponse, ExtractRequest>,
@@ -134,6 +135,17 @@ export async function extractController(
zeroDataRetention: req.acuc?.flags?.forceZDR,
});
+ await logRequest({
+ id: extractId,
+ kind: "extract",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.urls?.[0] ?? "",
+ zeroDataRetention: false, // not supported for extract
+ });
+
const scrapeOptions = req.body.scrapeOptions
? fromV1ScrapeOptions(
req.body.scrapeOptions,
diff --git a/apps/api/src/controllers/v1/generate-llmstxt-status.ts b/apps/api/src/controllers/v1/generate-llmstxt-status.ts
index 097a7ae29..3909d5564 100644
--- a/apps/api/src/controllers/v1/generate-llmstxt-status.ts
+++ b/apps/api/src/controllers/v1/generate-llmstxt-status.ts
@@ -4,7 +4,6 @@ import {
getGeneratedLlmsTxt,
getGeneratedLlmsTxtExpiry,
} from "../../lib/generate-llmstxt/generate-llmstxt-redis";
-import { supabaseGetJobsById } from "../../lib/supabase-jobs";
export async function generateLLMsTextStatusController(
req: RequestWithAuth<{ jobId: string }, any, any>,
diff --git a/apps/api/src/controllers/v1/generate-llmstxt.ts b/apps/api/src/controllers/v1/generate-llmstxt.ts
index d9974b92d..a7312bbe7 100644
--- a/apps/api/src/controllers/v1/generate-llmstxt.ts
+++ b/apps/api/src/controllers/v1/generate-llmstxt.ts
@@ -9,6 +9,7 @@ import {
import { getGenerateLlmsTxtQueue } from "../../services/queue-service";
import * as Sentry from "@sentry/node";
import { saveGeneratedLlmsTxt } from "../../lib/generate-llmstxt/generate-llmstxt-redis";
+import { logRequest } from "../../services/logging/log_job";
type GenerateLLMsTextResponse =
| ErrorResponse
@@ -38,6 +39,17 @@ export async function generateLLMsTextController(
req.body = generateLLMsTextRequestSchema.parse(req.body);
const generationId = uuidv7();
+
+ await logRequest({
+ id: generationId,
+ kind: "llmstxt",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: "api", // no origin field for llmstxt
+ target_hint: req.body.url,
+ zeroDataRetention: false, // not supported for llmstxt
+ });
+
const jobData = {
request: req.body,
teamId: req.auth.team_id,
diff --git a/apps/api/src/controllers/v1/map.ts b/apps/api/src/controllers/v1/map.ts
index 9dbf0f93f..ca514e954 100644
--- a/apps/api/src/controllers/v1/map.ts
+++ b/apps/api/src/controllers/v1/map.ts
@@ -18,7 +18,7 @@ import {
} from "../../lib/validateUrl";
import { fireEngineMap } from "../../search/fireEngine";
import { billTeam } from "../../services/billing/credit_billing";
-import { logJob } from "../../services/logging/log_job";
+import { logMap, logRequest } from "../../services/logging/log_job";
import { performCosineSimilarity } from "../../lib/map-cosine";
import { logger } from "../../lib/logger";
import Redis from "ioredis";
@@ -96,6 +96,7 @@ export async function getMapResults({
useIndex = true,
timeout,
location,
+ id: providedId,
}: {
url: string;
search?: string;
@@ -114,8 +115,9 @@ export async function getMapResults({
useIndex?: boolean;
timeout?: number;
location?: ScrapeOptions["location"];
+ id?: string;
}): Promise<MapResult> {
- const id = uuidv7();
+ const id = providedId ?? uuidv7();
let links: string[] = [url];
let mapResults: MapDocument[] = [];
@@ -376,10 +378,24 @@ export async function mapController(
const middlewareTime = controllerStartTime - middlewareStartTime;
+ const mapId = uuidv7();
+
logger.info("Map request", {
request: req.body,
originalRequest,
teamId: req.auth.team_id,
+ mapId,
+ });
+
+ await logRequest({
+ id: mapId,
+ kind: "map",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.url,
+ zeroDataRetention: false, // not supported for map
});
let result: Awaited<ReturnType<typeof getMapResults>>;
@@ -404,6 +420,7 @@ export async function mapController(
useIndex: req.body.useIndex,
timeout: req.body.timeout,
location: req.body.location,
+ id: mapId,
}),
...(req.body.timeout !== undefined
? [
@@ -446,22 +463,23 @@ export async function mapController(
});
// Log the job
- logJob({
- job_id: result.job_id,
- success: result.links.length > 0,
- message: "Map completed",
- num_docs: result.links.length,
- docs: result.links,
- time_taken: result.time_taken,
- team_id: req.auth.team_id,
- mode: "map",
+ logMap({
+ id: result.job_id,
+ request_id: result.job_id,
url: req.body.url,
- crawlerOptions: {},
- scrapeOptions: {},
- origin: req.body.origin ?? "api",
- integration: req.body.integration,
- num_tokens: 0,
- credits_billed: 1,
+ team_id: req.auth.team_id,
+ options: {
+ search: req.body.search,
+ limit: req.body.limit,
+ ignoreSitemap: req.body.ignoreSitemap,
+ includeSubdomains: req.body.includeSubdomains,
+ filterByPath: req.body.filterByPath !== false,
+ useIndex: req.body.useIndex,
+ timeout: req.body.timeout,
+ location: req.body.location,
+ },
+ results: result.links,
+ credits_cost: 1,
zeroDataRetention: false, // not supported
});
diff --git a/apps/api/src/controllers/v1/scrape-status.ts b/apps/api/src/controllers/v1/scrape-status.ts
index 18937e6e8..3cce861ce 100644
--- a/apps/api/src/controllers/v1/scrape-status.ts
+++ b/apps/api/src/controllers/v1/scrape-status.ts
@@ -1,5 +1,5 @@
import { Response } from "express";
-import { supabaseGetJobByIdOnlyData } from "../../lib/supabase-jobs";
+import { supabaseGetScrapeByIdOnlyData } from "../../lib/supabase-jobs";
import { getJob } from "./crawl-status";
import { logger as _logger } from "../../lib/logger";
@@ -21,7 +21,7 @@ export async function scrapeStatusController(req: any, res: any) {
});
}
- const job = await supabaseGetJobByIdOnlyData(req.params.jobId, logger);
+ const job = await supabaseGetScrapeByIdOnlyData(req.params.jobId, logger);
if (!job) {
return res.status(404).json({
diff --git a/apps/api/src/controllers/v1/scrape.ts b/apps/api/src/controllers/v1/scrape.ts
index ca3a18af2..050166915 100644
--- a/apps/api/src/controllers/v1/scrape.ts
+++ b/apps/api/src/controllers/v1/scrape.ts
@@ -17,6 +17,7 @@ import { teamConcurrencySemaphore } from "../../services/worker/team-semaphore";
import { processJobInternal } from "../../services/worker/scrape-worker";
import { ScrapeJobData } from "../../types";
import { AbortManagerThrownError } from "../../scraper/scrapeURL/lib/abortManager";
+import { logRequest } from "../../services/logging/log_job";
export async function scrapeController(
req: RequestWithAuth<{}, ScrapeResponse, ScrapeRequest>,
@@ -62,6 +63,17 @@ export async function scrapeController(
account: req.account,
});
+ await logRequest({
+ id: jobId,
+ kind: "scrape",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: req.body.origin,
+ integration: req.body.integration,
+ target_hint: req.body.url,
+ zeroDataRetention: zeroDataRetention || false,
+ });
+
const origin = req.body.origin;
const timeout = req.body.timeout;
diff --git a/apps/api/src/controllers/v1/search.ts b/apps/api/src/controllers/v1/search.ts
index 1058fe359..f901a13fa 100644
--- a/apps/api/src/controllers/v1/search.ts
+++ b/apps/api/src/controllers/v1/search.ts
@@ -11,7 +11,7 @@ import {
import { billTeam } from "../../services/billing/credit_billing";
import { v7 as uuidv7 } from "uuid";
import { addScrapeJob, waitForJob } from "../../services/queue-jobs";
-import { logJob } from "../../services/logging/log_job";
+import { logSearch, logRequest } from "../../services/logging/log_job";
import { search } from "../../search";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import * as Sentry from "@sentry/node";
@@ -40,6 +40,7 @@ export async function searchAndScrapeSearchResult(
timeout: number;
scrapeOptions: ScrapeOptions;
apiKeyId: number | null;
+ requestId?: string;
},
logger: Logger,
flags: TeamFlags,
@@ -80,6 +81,7 @@ async function scrapeSearchResult(
timeout: number;
scrapeOptions: ScrapeOptions;
apiKeyId: number | null;
+ requestId?: string;
},
logger: Logger,
flags: TeamFlags,
@@ -138,6 +140,7 @@ async function scrapeSearchResult(
startTime: Date.now(),
zeroDataRetention,
apiKeyId: options.apiKeyId,
+ requestId: options.requestId,
},
jobId,
jobPriority,
@@ -170,9 +173,9 @@ async function scrapeSearchResult(
if (process.env.USE_DB_AUTHENTICATION === "true") {
const { data: costTrackingResponse, error: costTrackingError } =
await supabase_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select("cost_tracking")
- .eq("job_id", jobId);
+ .eq("id", jobId);
if (costTrackingError) {
logger.error("Error getting cost tracking", {
@@ -268,6 +271,17 @@ export async function searchController(
origin: req.body.origin,
});
+ await logRequest({
+ id: jobId,
+ kind: "search",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.query,
+ zeroDataRetention: false, // not supported for search
+ });
+
let limit = req.body.limit;
// Buffer results by 50% to account for filtered URLs
@@ -326,6 +340,7 @@ export async function searchController(
timeout: req.body.timeout,
scrapeOptions: req.body.scrapeOptions,
apiKeyId: req.acuc?.api_key_id ?? null,
+ requestId: jobId,
},
logger,
req.acuc?.flags ?? null,
@@ -430,29 +445,26 @@ export async function searchController(
time_taken: timeTakenInSeconds,
});
- logJob(
+ logSearch(
{
- job_id: jobId,
- success: true,
- num_docs: responseData.data.length,
- docs: responseData.data,
+ id: jobId,
+ request_id: jobId,
+ query: req.body.query,
+ is_successful: true,
+ error: undefined,
+ results: responseData.data,
+ num_results: responseData.data.length,
time_taken: timeTakenInSeconds,
team_id: req.auth.team_id,
- mode: "search",
- url: req.body.query,
- scrapeOptions: req.body.scrapeOptions,
- crawlerOptions: {
+ options: {
...req.body,
query: undefined,
scrapeOptions: undefined,
},
- origin: req.body.origin,
- integration: req.body.integration,
- credits_billed,
+ credits_cost: credits_billed,
zeroDataRetention: false, // not supported
},
false,
- isSearchPreview,
);
// Log final timing information
diff --git a/apps/api/src/controllers/v1/x402-search.ts b/apps/api/src/controllers/v1/x402-search.ts
index 88b218fd0..7cfb39530 100644
--- a/apps/api/src/controllers/v1/x402-search.ts
+++ b/apps/api/src/controllers/v1/x402-search.ts
@@ -10,7 +10,7 @@ import {
} from "./types";
import { v7 as uuidv7 } from "uuid";
import { addScrapeJob, waitForJob } from "../../services/queue-jobs";
-import { logJob } from "../../services/logging/log_job";
+import { logSearch, logRequest } from "../../services/logging/log_job";
import { search } from "../../search";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import * as Sentry from "@sentry/node";
@@ -123,9 +123,9 @@ async function scrapeX402SearchResult(
if (process.env.USE_DB_AUTHENTICATION === "true") {
const { data: costTrackingResponse, error: costTrackingError } =
await supabase_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select("cost_tracking")
- .eq("job_id", jobId);
+ .eq("id", jobId);
if (costTrackingError) {
throw costTrackingError;
@@ -214,6 +214,17 @@ export async function x402SearchController(
origin: req.body.origin,
});
+ await logRequest({
+ id: jobId,
+ kind: "search",
+ api_version: "v1",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.query,
+ zeroDataRetention: false, // not supported for x402 search
+ });
+
let limit = req.body.limit;
// Buffer results by 50% to account for filtered URLs
@@ -310,29 +321,22 @@ export async function x402SearchController(
time_taken: timeTakenInSeconds,
});
- logJob(
+ logSearch(
{
- job_id: jobId,
- success: true,
- num_docs: responseData.data.length,
- docs: responseData.data,
+ id: jobId,
+ request_id: jobId,
+ query: req.body.query,
+ is_successful: true,
+ error: undefined,
+ results: responseData.data,
+ num_results: responseData.data.length,
time_taken: timeTakenInSeconds,
team_id: req.auth.team_id,
- mode: "x402-search",
- url: req.body.query,
- scrapeOptions: req.body.scrapeOptions,
- crawlerOptions: {
- ...req.body,
- query: undefined,
- scrapeOptions: undefined,
- },
- origin: req.body.origin,
- integration: req.body.integration,
- credits_billed: 0,
+ options: { ...req.body, scrapeOptions: undefined, query: undefined },
+ credits_cost: responseData.data.length,
zeroDataRetention: false, // not supported
},
false,
- isSearchPreview,
);
return res.status(200).json(responseData);
diff --git a/apps/api/src/controllers/v2/batch-scrape.ts b/apps/api/src/controllers/v2/batch-scrape.ts
index 6ad641ab2..02ca01a16 100644
--- a/apps/api/src/controllers/v2/batch-scrape.ts
+++ b/apps/api/src/controllers/v2/batch-scrape.ts
@@ -26,6 +26,7 @@ import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import { checkPermissions } from "../../lib/permissions";
import { crawlGroup } from "../../services/worker/nuq";
+import { logRequest } from "../../services/logging/log_job";
export async function batchScrapeController(
req: RequestWithAuth<{}, BatchScrapeResponse, BatchScrapeRequest>,
@@ -110,6 +111,19 @@ export async function batchScrapeController(
account: req.account,
});
+ if (!req.body.appendToId) {
+ await logRequest({
+ id,
+ kind: "batch_scrape",
+ api_version: "v2",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: urls[0] ?? "",
+ zeroDataRetention: zeroDataRetention || false,
+ });
+ }
+
const sc: StoredCrawl = req.body.appendToId
? ((await getCrawl(req.body.appendToId)) as StoredCrawl)
: {
diff --git a/apps/api/src/controllers/v2/crawl-errors.ts b/apps/api/src/controllers/v2/crawl-errors.ts
index f0899c616..55e1ad837 100644
--- a/apps/api/src/controllers/v2/crawl-errors.ts
+++ b/apps/api/src/controllers/v2/crawl-errors.ts
@@ -73,21 +73,22 @@ export async function crawlErrorsController(
),
});
} else if (process.env.USE_DB_AUTHENTICATION === "true") {
- const { data: crawlJobs, error: crawlJobError } = await supabase_rr_service
- .from("firecrawl_jobs")
+ // Check the requests table for the crawl/batch scrape request
+ const { data: request, error: requestError } = await supabase_rr_service
+ .from("requests")
.select("*")
- .eq("job_id", req.params.jobId)
+ .eq("id", req.params.jobId)
.limit(1)
.throwOnError();
- if (crawlJobError) {
- _logger.error("Error getting crawl job", { error: crawlJobError });
- throw crawlJobError;
+ if (requestError) {
+ _logger.error("Error getting request", { error: requestError });
+ throw requestError;
}
- const crawlJob = crawlJobs[0];
+ const requestData = request?.[0];
- if (crawlJob && crawlJob.team_id !== req.auth.team_id) {
+ if (requestData && requestData.team_id !== req.auth.team_id) {
return res.status(403).json({ success: false, error: "Forbidden" });
}
@@ -95,50 +96,53 @@ export async function crawlErrorsController(
const crawlTtlMs = crawlTtlHours * 60 * 60 * 1000;
if (
- crawlJob &&
- new Date().valueOf() - new Date(crawlJob.date_added).valueOf() >
+ requestData &&
+ new Date().valueOf() - new Date(requestData.created_at).valueOf() >
crawlTtlMs
) {
return res.status(404).json({ success: false, error: "Job expired" });
}
- if (!crawlJobs || crawlJobs.length === 0) {
+ if (!request || request.length === 0) {
return res.status(404).json({ success: false, error: "Job not found" });
}
- const { data: failedJobs, error: failedJobsError } =
+ // Get failed scrapes from the scrapes table
+ const { data: failedScrapes, error: failedScrapesError } =
await supabase_rr_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select("*")
- .eq("crawl_id", req.params.jobId)
+ .eq("request_id", req.params.jobId)
.eq("team_id", req.auth.team_id)
.eq("success", false)
.throwOnError();
- if (failedJobsError) {
- _logger.error("Error getting failed jobs", { error: failedJobsError });
- throw failedJobsError;
+ if (failedScrapesError) {
+ _logger.error("Error getting failed scrapes", {
+ error: failedScrapesError,
+ });
+ throw failedScrapesError;
}
res.status(200).json({
- errors: (failedJobs || []).map(job => {
+ errors: (failedScrapes || []).map(scrape => {
const error = deserializeTransportableError(
- job.message,
+ scrape.error,
) as TransportableError | null;
return {
- id: job.job_id,
+ id: scrape.id,
timestamp:
- job.finishedOn !== undefined
- ? new Date(job.finishedOn).toISOString()
+ scrape.created_at !== undefined
+ ? new Date(scrape.created_at).toISOString()
: undefined,
- url: job.url,
+ url: scrape.url,
...(error
? {
code: error.code,
error: error.message,
}
: {
- error: job.message,
+ error: scrape.error,
}),
};
}),
diff --git a/apps/api/src/controllers/v2/crawl-status.ts b/apps/api/src/controllers/v2/crawl-status.ts
index ee7d4692a..d6af4d726 100644
--- a/apps/api/src/controllers/v2/crawl-status.ts
+++ b/apps/api/src/controllers/v2/crawl-status.ts
@@ -14,8 +14,8 @@ import {
isCrawlKickoffFinished,
} from "../../lib/crawl-redis";
import {
- supabaseGetJobById,
- supabaseGetJobsById,
+ supabaseGetScrapeById,
+ supabaseGetScrapesById,
} from "../../lib/supabase-jobs";
import { configDotenv } from "dotenv";
import { logger } from "../../lib/logger";
@@ -44,12 +44,12 @@ export type PseudoJob<T> = {
failedReason?: string;
};
-export type DBJob = {
- docs: any;
+type DBScrape = {
+ id: string;
success: boolean;
- page_options: any;
- date_added: any;
- message: string | null;
+ options: any;
+ created_at: any;
+ error: string | null;
team_id: string;
};
@@ -57,26 +57,26 @@ export async function getJob(
id: string,
_logger = logger,
): Promise<PseudoJob<any> | null> {
- const [nuqJob, dbJob, gcsJob] = await Promise.all([
+ const [nuqJob, dbScrape, gcsJob] = await Promise.all([
scrapeQueue.getJob(
id,
_logger,
) as Promise<NuQJob<ScrapeJobSingleUrls> | null>,
(process.env.USE_DB_AUTHENTICATION === "true"
- ? supabaseGetJobById(id)
- : null) as Promise<DBJob | null>,
+ ? supabaseGetScrapeById(id)
+ : null) as Promise<DBScrape | null>,
(process.env.GCS_BUCKET_NAME ? getJobFromGCS(id) : null) as Promise<
any | null
>,
]);
- if (!nuqJob && !dbJob) return null;
+ if (!nuqJob && !dbScrape) return null;
if (nuqJob && nuqJob.data.mode !== "single_urls") {
return null;
}
- const data = gcsJob ?? dbJob?.docs ?? nuqJob?.returnvalue;
+ const data = gcsJob ?? nuqJob?.returnvalue;
if (gcsJob === null && data) {
_logger.warn("GCS Job not found", {
jobId: id,
@@ -85,15 +85,19 @@ export async function getJob(
const job: PseudoJob<any> = {
id,
- status: dbJob ? (dbJob.success ? "completed" : "failed") : nuqJob!.status,
+ status: dbScrape
+ ? dbScrape.success
+ ? "completed"
+ : "failed"
+ : nuqJob!.status,
returnvalue: Array.isArray(data) ? data[0] : data,
data: {
- scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbJob!.page_options,
+ scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbScrape!.options,
},
timestamp: nuqJob
? nuqJob.createdAt.valueOf()
- : new Date(dbJob!.date_added).valueOf(),
- failedReason: (nuqJob ? nuqJob.failedReason : dbJob!.message) || undefined,
+ : new Date(dbScrape!.created_at).valueOf(),
+ failedReason: (nuqJob ? nuqJob.failedReason : dbScrape!.error) || undefined,
};
return job;
@@ -103,10 +107,10 @@ export async function getJobs(
ids: string[],
_logger = logger,
): Promise<PseudoJob<any>[]> {
- const [nuqJobs, dbJobs, gcsJobs] = await Promise.all([
+ const [nuqJobs, dbScrapes, gcsJobs] = await Promise.all([
scrapeQueue.getJobs(ids, _logger) as Promise<NuQJob<ScrapeJobSingleUrls>[]>,
process.env.USE_DB_AUTHENTICATION === "true"
- ? supabaseGetJobsById(ids)
+ ? supabaseGetScrapesById(ids)
: [],
process.env.GCS_BUCKET_NAME
? (Promise.all(
@@ -118,15 +122,15 @@ export async function getJobs(
]);
const nuqJobMap = new Map<string, NuQJob<any, any>>();
- const dbJobMap = new Map<string, DBJob>();
+ const dbScrapeMap = new Map<string, DBScrape>();
const gcsJobMap = new Map<string, any>();
for (const job of nuqJobs) {
nuqJobMap.set(job.id, job);
}
- for (const job of dbJobs) {
- dbJobMap.set(job.job_id, job);
+ for (const scrape of dbScrapes) {
+ dbScrapeMap.set(scrape.id, scrape);
}
for (const job of gcsJobs) {
@@ -137,12 +141,12 @@ export async function getJobs(
for (const id of ids) {
const nuqJob = nuqJobMap.get(id);
- const dbJob = dbJobMap.get(id);
+ const dbScrape = dbScrapeMap.get(id);
const gcsJob = gcsJobMap.get(id);
- if (!nuqJob && !dbJob) continue;
+ if (!nuqJob && !dbScrape) continue;
- const data = gcsJob ?? dbJob?.docs ?? nuqJob?.returnvalue;
+ const data = gcsJob ?? nuqJob?.returnvalue;
if (gcsJob === null && data) {
logger.warn("GCS Job not found", {
jobId: id,
@@ -151,16 +155,20 @@ export async function getJobs(
const job: PseudoJob<any> = {
id,
- status: dbJob ? (dbJob.success ? "completed" : "failed") : nuqJob!.status,
+ status: dbScrape
+ ? dbScrape.success
+ ? "completed"
+ : "failed"
+ : nuqJob!.status,
returnvalue: Array.isArray(data) ? data[0] : data,
data: {
- scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbJob!.page_options,
+ scrapeOptions: nuqJob ? nuqJob.data.scrapeOptions : dbScrape!.options,
},
timestamp: nuqJob
? nuqJob.createdAt.valueOf()
- : new Date(dbJob!.date_added).valueOf(),
+ : new Date(dbScrape!.created_at).valueOf(),
failedReason:
- (nuqJob ? nuqJob.failedReason : dbJob!.message) || undefined,
+ (nuqJob ? nuqJob.failedReason : dbScrape!.error) || undefined,
};
jobs.push(job);
@@ -213,7 +221,7 @@ export async function crawlStatusController(
const creditsRpc =
process.env.USE_DB_AUTHENTICATION === "true"
? await supabase_service.rpc(
- "credits_billed_by_crawl_id_1",
+ "credits_billed_by_crawl_id_2",
{
i_crawl_id: req.params.jobId,
},
diff --git a/apps/api/src/controllers/v2/crawl.ts b/apps/api/src/controllers/v2/crawl.ts
index 5beba6eea..babd3a0dd 100644
--- a/apps/api/src/controllers/v2/crawl.ts
+++ b/apps/api/src/controllers/v2/crawl.ts
@@ -21,6 +21,7 @@ import { checkPermissions } from "../../lib/permissions";
import { buildPromptWithWebsiteStructure } from "../../lib/map-utils";
import { modifyCrawlUrl } from "../../utils/url-utils";
import { crawlGroup } from "../../services/worker/nuq";
+import { logRequest } from "../../services/logging/log_job";
export async function crawlController(
req: RequestWithAuth<{}, CrawlResponse, CrawlRequest>,
@@ -59,6 +60,17 @@ export async function crawlController(
account: req.account,
});
+ await logRequest({
+ id,
+ kind: "crawl",
+ api_version: "v2",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.url,
+ zeroDataRetention: zeroDataRetention || false,
+ });
+
let { remainingCredits } = req.account!;
const useDbAuthentication = process.env.USE_DB_AUTHENTICATION === "true";
if (!useDbAuthentication) {
@@ -229,7 +241,7 @@ export async function crawlController(
zeroDataRetention: zeroDataRetention || false,
apiKeyId: req.acuc?.api_key_id ?? null,
},
- crypto.randomUUID(),
+ uuidv7(),
);
const protocol = req.protocol;
diff --git a/apps/api/src/controllers/v2/extract-status.ts b/apps/api/src/controllers/v2/extract-status.ts
index f68081d54..80604a589 100644
--- a/apps/api/src/controllers/v2/extract-status.ts
+++ b/apps/api/src/controllers/v2/extract-status.ts
@@ -1,13 +1,21 @@
import { Response } from "express";
import { RequestWithAuth } from "./types";
import { getExtract, getExtractExpiry } from "../../lib/extract/extract-redis";
-import { DBJob } from "./crawl-status";
import { getExtractQueue } from "../../services/queue-service";
import { ExtractResult } from "../../lib/extract/extraction-service";
-import { supabaseGetJobByIdDirect } from "../../lib/supabase-jobs";
+import { supabaseGetExtractByIdDirect } from "../../lib/supabase-jobs";
import { JobState } from "bullmq";
import { logger as _logger } from "../../lib/logger";
+type DBExtract = {
+ id: string;
+ success: boolean;
+ options: any;
+ created_at: any;
+ error: string | null;
+ team_id: string;
+};
+
type ExtractPseudoJob<T> = {
id: string;
getState: () => Promise<JobState | "unknown"> | JobState | "unknown";
@@ -23,32 +31,33 @@ type ExtractPseudoJob<T> = {
async function getExtractJob(
id: string,
): Promise<ExtractPseudoJob<ExtractResult> | null> {
- const [bullJob, dbJob] = await Promise.all([
+ const [bullJob, dbExtract] = await Promise.all([
getExtractQueue().getJob(id),
(process.env.USE_DB_AUTHENTICATION === "true"
- ? supabaseGetJobByIdDirect(id)
- : null) as Promise<DBJob | null>,
+ ? supabaseGetExtractByIdDirect(id)
+ : null) as Promise<DBExtract | null>,
]);
- if (!bullJob && !dbJob) return null;
+ if (!bullJob && !dbExtract) return null;
- const data = dbJob?.docs ?? bullJob?.returnvalue?.data;
+ // Extract results are stored in GCS, not in the DB
+ const data = bullJob?.returnvalue?.data;
const job: ExtractPseudoJob<any> = {
id,
getState: bullJob
? bullJob.getState.bind(bullJob)
- : () => (dbJob!.success ? "completed" : "failed"),
+ : () => (dbExtract!.success ? "completed" : "failed"),
returnvalue: data,
data: {
- scrapeOptions: bullJob ? bullJob.data.scrapeOptions : dbJob!.page_options,
- teamId: bullJob ? bullJob.data.teamId : dbJob!.team_id,
+ scrapeOptions: bullJob ? bullJob.data.scrapeOptions : dbExtract!.options,
+ teamId: bullJob ? bullJob.data.teamId : dbExtract!.team_id,
},
timestamp: bullJob
? bullJob.timestamp
- : new Date(dbJob!.date_added).valueOf(),
+ : new Date(dbExtract!.created_at).valueOf(),
failedReason:
- (bullJob ? bullJob.failedReason : dbJob!.message) || undefined,
+ (bullJob ? bullJob.failedReason : dbExtract!.error) || undefined,
};
return job;
diff --git a/apps/api/src/controllers/v2/extract.ts b/apps/api/src/controllers/v2/extract.ts
index 740f952f6..b8bbdb525 100644
--- a/apps/api/src/controllers/v2/extract.ts
+++ b/apps/api/src/controllers/v2/extract.ts
@@ -11,6 +11,7 @@ import { saveExtract } from "../../lib/extract/extract-redis";
import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import { logger as _logger } from "../../lib/logger";
+import { logRequest } from "../../services/logging/log_job";
/**
* Extracts data from the provided URLs based on the request parameters.
@@ -60,6 +61,17 @@ export async function extractController(
zeroDataRetention: req.acuc?.flags?.forceZDR,
});
+ await logRequest({
+ id: extractId,
+ kind: "extract",
+ api_version: "v2",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.urls?.[0] ?? "",
+ zeroDataRetention: false, // not supported for extract
+ });
+
const jobData = {
request: req.body,
teamId: req.auth.team_id,
diff --git a/apps/api/src/controllers/v2/map.ts b/apps/api/src/controllers/v2/map.ts
index be2f78424..5764929e8 100644
--- a/apps/api/src/controllers/v2/map.ts
+++ b/apps/api/src/controllers/v2/map.ts
@@ -4,11 +4,10 @@ import {
RequestWithAuth,
MapRequest,
MapResponse,
- MAX_MAP_LIMIT,
} from "./types";
import { configDotenv } from "dotenv";
import { billTeam } from "../../services/billing/credit_billing";
-import { logJob } from "../../services/logging/log_job";
+import { logMap, logRequest } from "../../services/logging/log_job";
import { logger as _logger } from "../../lib/logger";
import { MapTimeoutError } from "../../lib/error";
import { checkPermissions } from "../../lib/permissions";
@@ -47,10 +46,24 @@ export async function mapController(
const middlewareTime = controllerStartTime - middlewareStartTime;
+ const mapId = uuidv7();
+
logger.info("Map request", {
request: req.body,
originalRequest,
teamId: req.auth.team_id,
+ mapId,
+ });
+
+ await logRequest({
+ id: mapId,
+ kind: "map",
+ api_version: "v2",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.url,
+ zeroDataRetention: false, // not supported for map
});
let result: MapResult;
@@ -77,6 +90,7 @@ export async function mapController(
flags: req.acuc?.flags ?? null,
useIndex: req.body.useIndex,
location: req.body.location,
+ id: mapId,
}),
...(req.body.timeout !== undefined
? [
@@ -118,36 +132,22 @@ export async function mapController(
);
});
- // Log the job
- const mapCrawlerOptions = {
- search: req.body.search,
- sitemap: req.body.sitemap,
- includeSubdomains: req.body.includeSubdomains,
- ignoreQueryParameters: req.body.ignoreQueryParameters,
- limit: req.body.limit,
- timeout: req.body.timeout,
- };
-
- const mapScrapeOptions = {
- location: req.body.location,
- };
-
- logJob({
- job_id: result.job_id,
- success: result.mapResults.length > 0,
- message: "Map completed",
- num_docs: result.mapResults.length,
- docs: result.mapResults,
- time_taken: result.time_taken,
- team_id: req.auth.team_id,
- mode: "map",
+ logMap({
+ id: result.job_id,
+ request_id: result.job_id,
url: req.body.url,
- crawlerOptions: mapCrawlerOptions,
- scrapeOptions: mapScrapeOptions,
- origin: req.body.origin ?? "api",
- integration: req.body.integration,
- num_tokens: 0,
- credits_billed: 1,
+ team_id: req.auth.team_id,
+ options: {
+ search: req.body.search,
+ sitemap: req.body.sitemap,
+ includeSubdomains: req.body.includeSubdomains,
+ ignoreQueryParameters: req.body.ignoreQueryParameters,
+ limit: req.body.limit,
+ timeout: req.body.timeout,
+ location: req.body.location,
+ },
+ results: result.mapResults,
+ credits_cost: 1,
zeroDataRetention: false, // not supported
}).catch(error => {
logger.error(`Failed to log job for team ${req.auth.team_id}: ${error}`);
diff --git a/apps/api/src/controllers/v2/scrape-status.ts b/apps/api/src/controllers/v2/scrape-status.ts
index 5e0252025..2fa51cbfc 100644
--- a/apps/api/src/controllers/v2/scrape-status.ts
+++ b/apps/api/src/controllers/v2/scrape-status.ts
@@ -1,4 +1,4 @@
-import { supabaseGetJobByIdOnlyData } from "../../lib/supabase-jobs";
+import { supabaseGetScrapeByIdOnlyData } from "../../lib/supabase-jobs";
import { getJob } from "./crawl-status";
import { logger as _logger } from "../../lib/logger";
@@ -29,7 +29,7 @@ export async function scrapeStatusController(req: any, res: any) {
});
}
- const job = await supabaseGetJobByIdOnlyData(req.params.jobId, logger);
+ const job = await supabaseGetScrapeByIdOnlyData(req.params.jobId, logger);
if (!job) {
return res.status(404).json({
diff --git a/apps/api/src/controllers/v2/scrape.ts b/apps/api/src/controllers/v2/scrape.ts
index d70be9cca..34e524573 100644
--- a/apps/api/src/controllers/v2/scrape.ts
+++ b/apps/api/src/controllers/v2/scrape.ts
@@ -18,6 +18,7 @@ import { processJobInternal } from "../../services/worker/scrape-worker";
import { ScrapeJobData } from "../../types";
import { teamConcurrencySemaphore } from "../../services/worker/team-semaphore";
import { getJobPriority } from "../../lib/job-priority";
+import { logRequest } from "../../services/logging/log_job";
export async function scrapeController(
req: RequestWithAuth<{}, ScrapeResponse, ScrapeRequest>,
@@ -98,6 +99,17 @@ export async function scrapeController(
account: req.account,
});
+ await logRequest({
+ id: jobId,
+ kind: "scrape",
+ api_version: "v2",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.url,
+ zeroDataRetention: zeroDataRetention || false,
+ });
+
setSpanAttributes(span, {
"scrape.zero_data_retention": zeroDataRetention,
"scrape.origin": req.body.origin,
diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.ts
index 4b6534119..957cd336f 100644
--- a/apps/api/src/controllers/v2/search.ts
+++ b/apps/api/src/controllers/v2/search.ts
@@ -11,7 +11,7 @@ import {
import { billTeam } from "../../services/billing/credit_billing";
import { v7 as uuidv7 } from "uuid";
import { addScrapeJob, waitForJob } from "../../services/queue-jobs";
-import { logJob } from "../../services/logging/log_job";
+import { logSearch, logRequest } from "../../services/logging/log_job";
import { search } from "../../search/v2";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import * as Sentry from "@sentry/node";
@@ -52,6 +52,7 @@ async function startScrapeJob(
bypassBilling?: boolean;
apiKeyId: number | null;
zeroDataRetention?: boolean;
+ requestId?: string;
},
logger: Logger,
flags: TeamFlags,
@@ -97,6 +98,7 @@ async function startScrapeJob(
startTime: Date.now(),
zeroDataRetention,
apiKeyId: options.apiKeyId,
+ requestId: options.requestId,
},
jobId,
jobPriority,
@@ -117,6 +119,7 @@ async function scrapeSearchResult(
bypassBilling?: boolean;
apiKeyId: number | null;
zeroDataRetention?: boolean;
+ requestId?: string;
},
logger: Logger,
flags: TeamFlags,
@@ -134,7 +137,12 @@ async function scrapeSearchResult(
isSearchPreview,
);
- const doc: Document = await waitForJob(jobId, options.timeout, false);
+ const doc: Document = await waitForJob(
+ jobId,
+ options.timeout,
+ options.zeroDataRetention ?? false,
+ logger,
+ );
logger.info("Scrape job completed", {
scrapeId: jobId,
@@ -156,9 +164,9 @@ async function scrapeSearchResult(
if (process.env.USE_DB_AUTHENTICATION === "true") {
const { data: costTrackingResponse, error: costTrackingError } =
await supabase_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select("cost_tracking")
- .eq("job_id", jobId);
+ .eq("id", jobId);
if (costTrackingError) {
logger.error("Error getting cost tracking", {
@@ -242,6 +250,21 @@ export async function searchController(
origin: req.body.origin,
});
+ const isZDR = req.body.enterprise?.includes("zdr");
+ const isAnon = req.body.enterprise?.includes("anon");
+ const isZDROrAnon = isZDR || isAnon;
+
+ await logRequest({
+ id: jobId,
+ kind: "search",
+ api_version: "v2",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.query,
+ zeroDataRetention: isZDROrAnon ?? false, // not supported for search
+ });
+
let limit = req.body.limit;
// Buffer results by 50% to account for filtered URLs
@@ -253,10 +276,6 @@ export async function searchController(
// After transformation, sources is always an array of objects
const searchTypes = [...new Set(req.body.sources.map((s: any) => s.type))];
- const isZDR = req.body.enterprise?.includes("zdr");
- const isAnon = req.body.enterprise?.includes("anon");
- const isZDROrAnon = isZDR || isAnon;
-
// Build search query with category filters
const { query: searchQuery, categoryMap } = buildSearchQuery(
req.body.query,
@@ -346,6 +365,7 @@ export async function searchController(
bypassBilling: !isAsyncScraping, // Async mode bills per job, sync mode bills manually
apiKeyId: req.acuc?.api_key_id ?? null,
zeroDataRetention: isZDROrAnon,
+ requestId: jobId,
};
const directToBullMQ = (req.acuc?.price_credits ?? 0) <= 3000;
@@ -507,35 +527,24 @@ export async function searchController(
time_taken: timeTakenInSeconds,
scrapeIds,
});
- if (!isZDROrAnon) {
- logJob(
- {
- job_id: jobId,
- success: true,
- num_docs:
- (searchResponse.web?.length ?? 0) +
- (searchResponse.images?.length ?? 0) +
- (searchResponse.news?.length ?? 0),
- docs: [searchResponse],
- time_taken: timeTakenInSeconds,
- team_id: req.auth.team_id,
- mode: "search",
- url: req.body.query,
- scrapeOptions: req.body.scrapeOptions,
- crawlerOptions: {
- ...req.body,
- query: undefined,
- scrapeOptions: undefined,
- },
- origin: req.body.origin,
- integration: req.body.integration,
- credits_billed,
- zeroDataRetention: false,
- },
- false,
- isSearchPreview,
- );
- }
+
+ logSearch(
+ {
+ id: jobId,
+ request_id: jobId,
+ query: req.body.query,
+ is_successful: true,
+ error: undefined,
+ results: searchResponse as any,
+ num_results: totalResultsCount,
+ time_taken: timeTakenInSeconds,
+ team_id: req.auth.team_id,
+ options: req.body,
+ credits_cost: credits_billed,
+ zeroDataRetention: isZDROrAnon ?? false,
+ },
+ false,
+ );
// Log final timing information for async mode
const totalRequestTime = new Date().getTime() - middlewareStartTime;
@@ -667,40 +676,28 @@ export async function searchController(
const endTime = new Date().getTime();
const timeTakenInSeconds = (endTime - middlewareStartTime) / 1000;
- if (!isZDROrAnon) {
- logger.info("Logging job", {
- num_docs: credits_billed,
+ logger.info("Logging job", {
+ num_docs: credits_billed,
+ time_taken: timeTakenInSeconds,
+ });
+
+ logSearch(
+ {
+ id: jobId,
+ request_id: jobId,
+ query: req.body.query,
+ is_successful: true,
+ error: undefined,
+ results: searchResponse as any,
+ num_results: totalResultsCount,
time_taken: timeTakenInSeconds,
- });
- logJob(
- {
- job_id: jobId,
- success: true,
- num_docs:
- (searchResponse.web?.length ?? 0) +
- (searchResponse.images?.length ?? 0) +
- (searchResponse.news?.length ?? 0),
- docs: [searchResponse],
- time_taken: timeTakenInSeconds,
- team_id: req.auth.team_id,
- mode: "search",
- url: req.body.query,
- scrapeOptions: req.body.scrapeOptions,
- crawlerOptions: {
- ...req.body,
- query: undefined,
- scrapeOptions: undefined,
- asyncScraping: isAsyncScraping,
- },
- origin: req.body.origin,
- integration: req.body.integration,
- credits_billed,
- zeroDataRetention: false, // not supported
- },
- false,
- isSearchPreview,
- );
- }
+ team_id: req.auth.team_id,
+ options: req.body,
+ credits_cost: credits_billed,
+ zeroDataRetention: isZDROrAnon ?? false, // not supported
+ },
+ false,
+ );
// Log final timing information
const totalRequestTime = new Date().getTime() - middlewareStartTime;
diff --git a/apps/api/src/controllers/v2/x402-search.ts b/apps/api/src/controllers/v2/x402-search.ts
index 1ad45b71c..84953830d 100644
--- a/apps/api/src/controllers/v2/x402-search.ts
+++ b/apps/api/src/controllers/v2/x402-search.ts
@@ -10,7 +10,7 @@ import {
} from "./types";
import { v7 as uuidv7 } from "uuid";
import { addScrapeJob, waitForJob } from "../../services/queue-jobs";
-import { logJob } from "../../services/logging/log_job";
+import { logSearch, logRequest } from "../../services/logging/log_job";
import { search } from "../../search/v2";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import * as Sentry from "@sentry/node";
@@ -151,9 +151,9 @@ async function scrapeX420SearchResult(
if (process.env.USE_DB_AUTHENTICATION === "true") {
const { data: costTrackingResponse, error: costTrackingError } =
await supabase_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select("cost_tracking")
- .eq("job_id", jobId);
+ .eq("id", jobId);
if (costTrackingError) {
logger.error("Error getting cost tracking [x402]", {
@@ -237,6 +237,17 @@ export async function x402SearchController(
origin: req.body.origin,
});
+ await logRequest({
+ id: jobId,
+ kind: "search",
+ api_version: "v2",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.query,
+ zeroDataRetention: false, // not supported for x402 search
+ });
+
let limit = req.body.limit;
// Buffer results by 50% to account for filtered URLs
@@ -483,32 +494,26 @@ export async function x402SearchController(
scrapeIds,
});
- logJob(
+ logSearch(
{
- job_id: jobId,
- success: true,
- num_docs:
- (searchResponse.web?.length ?? 0) +
- (searchResponse.images?.length ?? 0) +
- (searchResponse.news?.length ?? 0),
- docs: [searchResponse],
+ id: jobId,
+ request_id: jobId,
+ query: req.body.query,
+ is_successful: true,
+ error: undefined,
+ results: searchResponse as any,
+ num_results: totalResultsCount,
time_taken: timeTakenInSeconds,
team_id: req.auth.team_id,
- mode: "search",
- url: req.body.query,
- scrapeOptions: req.body.scrapeOptions,
- crawlerOptions: {
+ options: {
...req.body,
query: undefined,
scrapeOptions: undefined,
},
- origin: req.body.origin,
- integration: req.body.integration,
- credits_billed,
+ credits_cost: credits_billed,
zeroDataRetention: false,
},
false,
- isSearchPreview,
);
return res.status(200).json({
@@ -577,33 +582,22 @@ export async function x402SearchController(
time_taken: timeTakenInSeconds,
});
- logJob(
+ logSearch(
{
- job_id: jobId,
- success: true,
- num_docs:
- (searchResponse.web?.length ?? 0) +
- (searchResponse.images?.length ?? 0) +
- (searchResponse.news?.length ?? 0),
- docs: [searchResponse],
+ id: jobId,
+ request_id: jobId,
+ query: req.body.query,
+ is_successful: true,
+ error: undefined,
+ results: searchResponse as any,
+ num_results: totalResultsCount,
time_taken: timeTakenInSeconds,
team_id: req.auth.team_id,
- mode: "search",
- url: req.body.query,
- scrapeOptions: req.body.scrapeOptions,
- crawlerOptions: {
- ...req.body,
- query: undefined,
- scrapeOptions: undefined,
- asyncScraping: isAsyncScraping,
- },
- origin: req.body.origin,
- integration: req.body.integration,
- credits_billed,
+ options: { ...req.body, scrapeOptions: undefined, query: undefined },
+ credits_cost: credits_billed,
zeroDataRetention: false, // not supported
},
false,
- isSearchPreview,
);
// For sync scraping or no scraping, don't include scrapeIds
diff --git a/apps/api/src/lib/bigquery-jobs.ts b/apps/api/src/lib/bigquery-jobs.ts
deleted file mode 100644
index 41517e30b..000000000
--- a/apps/api/src/lib/bigquery-jobs.ts
+++ /dev/null
@@ -1,370 +0,0 @@
-import { FirecrawlJob } from "../types";
-import { logger } from "./logger";
-import { transformJobForLogging, createJobLoggerContext } from "./job-transform";
-
-// BigQuery client will be imported conditionally to avoid errors if not installed
-let BigQuery: any = null;
-let bigquery: any = null;
-
-try {
- // Dynamically import BigQuery to handle cases where it's not installed
- BigQuery = require("@google-cloud/bigquery").BigQuery;
-
- const credentials = process.env.GCS_CREDENTIALS
- ? JSON.parse(atob(process.env.GCS_CREDENTIALS))
- : undefined;
-
- bigquery = new BigQuery({
- projectId: process.env.GOOGLE_CLOUD_PROJECT_ID || "firecrawl",
- credentials,
- });
-} catch (error) {
- logger.warn("BigQuery client not available. BigQuery logging will be disabled.", {
- error: error.message,
- });
-}
-
-/**
- * Transforms a FirecrawlJob into a BigQuery-compatible row
- */
-function transformJobForBigQuery(job: FirecrawlJob) {
- const transformed = transformJobForLogging(job, {
- includeTimestamp: true,
- serializeObjects: true,
- cleanNullValues: false, // BigQuery handles null values fine
- });
-
- // Remove docs field from BigQuery to reduce storage costs and avoid size issues
- const { docs, ...bigQueryRow } = transformed;
-
- return bigQueryRow;
-}
-
-/**
- * Ensures the BigQuery dataset exists
- */
-async function ensureBigQueryDataset(): Promise<void> {
- if (!bigquery || !process.env.BIGQUERY_DATASET_ID) {
- return;
- }
-
- try {
- const datasetId = process.env.BIGQUERY_DATASET_ID;
- const dataset = bigquery.dataset(datasetId);
-
- const [exists] = await dataset.exists();
- if (!exists) {
- logger.info("Creating BigQuery dataset", { dataset: datasetId });
-
- await dataset.create({
- location: process.env.BIGQUERY_LOCATION || "US",
- });
-
- logger.info("BigQuery dataset created successfully", { dataset: datasetId });
- }
- } catch (error) {
- logger.error("Error ensuring BigQuery dataset exists", {
- error,
- dataset: process.env.BIGQUERY_DATASET_ID,
- });
- throw error;
- }
-}
-
-/**
- * Creates the BigQuery table if it doesn't exist
- */
-async function ensureBigQueryTable(): Promise<void> {
- if (!bigquery || !process.env.BIGQUERY_DATASET_ID) {
- return;
- }
-
- try {
- // Ensure dataset exists first
- // No need once it is initialized
- // await ensureBigQueryDataset();
-
- const datasetId = process.env.BIGQUERY_DATASET_ID;
- const tableId = process.env.BIGQUERY_TABLE_ID || "firecrawl_jobs";
-
- const dataset = bigquery.dataset(datasetId);
- const table = dataset.table(tableId);
-
- const [exists] = await table.exists();
-
- if (exists) {
- // Table exists, but let's check if it has the correct schema (without docs field)
- try {
- const [metadata] = await table.getMetadata();
- const currentSchema = metadata.schema;
-
- if (!currentSchema || !currentSchema.fields || currentSchema.fields.length === 0) {
- logger.warn("Table exists but has no schema, recreating table", {
- dataset: datasetId,
- table: tableId,
- });
-
- // Delete and recreate the table
- await table.delete();
- logger.info("Deleted table with no schema", { dataset: datasetId, table: tableId });
- } else {
- // Check if the table has the old schema with docs field or wrong data types
- const hasDocsField = currentSchema.fields.some((field: any) => field.name === 'docs');
- const timeTakenField = currentSchema.fields.find((field: any) => field.name === 'time_taken');
- const numTokensField = currentSchema.fields.find((field: any) => field.name === 'num_tokens');
- const hasWrongTimeTakenType = timeTakenField && timeTakenField.type !== 'FLOAT';
- const hasWrongNumTokensType = numTokensField && numTokensField.type !== 'FLOAT';
-
- if (hasDocsField) {
- logger.warn("Table has old schema with docs field, recreating table", {
- dataset: datasetId,
- table: tableId,
- });
-
- // Delete and recreate the table without docs field
- await table.delete();
- logger.info("Deleted table with old schema (docs field)", { dataset: datasetId, table: tableId });
- } else if (hasWrongTimeTakenType || hasWrongNumTokensType) {
- logger.warn("Table has wrong data types for numeric fields, recreating table", {
- dataset: datasetId,
- table: tableId,
- timeTakenType: timeTakenField?.type,
- numTokensType: numTokensField?.type,
- expectedType: 'FLOAT',
- });
-
- // Delete and recreate the table with correct data types
- await table.delete();
- logger.info("Deleted table with wrong schema (numeric field types)", { dataset: datasetId, table: tableId });
- } else {
- logger.debug("BigQuery table exists and has correct schema", {
- dataset: datasetId,
- table: tableId,
- });
- return;
- }
- }
- } catch (schemaError) {
- logger.error("Error checking table schema, recreating table", {
- error: schemaError,
- dataset: datasetId,
- table: tableId,
- });
-
- // Try to delete and recreate
- try {
- await table.delete();
- logger.info("Deleted problematic table", { dataset: datasetId, table: tableId });
- } catch (deleteError) {
- logger.error("Error deleting problematic table", { error: deleteError });
- }
- }
- }
-
- // Create the table (either it doesn't exist or we deleted it)
- logger.info("Creating BigQuery table", {
- dataset: datasetId,
- table: tableId,
- });
-
- const schema = [
- { name: "job_id", type: "STRING", mode: "NULLABLE" },
- { name: "success", type: "BOOLEAN", mode: "NULLABLE" },
- { name: "message", type: "STRING", mode: "NULLABLE" },
- { name: "num_docs", type: "INTEGER", mode: "NULLABLE" },
- // Note: docs field excluded from BigQuery to reduce storage costs and avoid size issues
- { name: "time_taken", type: "FLOAT", mode: "NULLABLE" },
- { name: "team_id", type: "STRING", mode: "NULLABLE" },
- { name: "mode", type: "STRING", mode: "NULLABLE" },
- { name: "url", type: "STRING", mode: "NULLABLE" },
- { name: "crawler_options", type: "STRING", mode: "NULLABLE" },
- { name: "page_options", type: "STRING", mode: "NULLABLE" },
- { name: "origin", type: "STRING", mode: "NULLABLE" },
- { name: "integration", type: "STRING", mode: "NULLABLE" },
- { name: "num_tokens", type: "FLOAT", mode: "NULLABLE" },
- { name: "retry", type: "BOOLEAN", mode: "NULLABLE" },
- { name: "crawl_id", type: "STRING", mode: "NULLABLE" },
- { name: "tokens_billed", type: "INTEGER", mode: "NULLABLE" },
- { name: "is_migrated", type: "BOOLEAN", mode: "NULLABLE" },
- { name: "cost_tracking", type: "STRING", mode: "NULLABLE" },
- { name: "pdf_num_pages", type: "INTEGER", mode: "NULLABLE" },
- { name: "credits_billed", type: "INTEGER", mode: "NULLABLE" },
- { name: "change_tracking_tag", type: "STRING", mode: "NULLABLE" },
- { name: "dr_clean_by", type: "TIMESTAMP", mode: "NULLABLE" },
- { name: "timestamp", type: "TIMESTAMP", mode: "NULLABLE" },
- ];
-
- const options = {
- schema: { fields: schema },
- timePartitioning: {
- type: "HOUR",
- field: "timestamp",
- },
- location: process.env.BIGQUERY_LOCATION || "US",
- };
-
- await table.create(options);
-
- logger.info("BigQuery table created successfully", {
- dataset: datasetId,
- table: tableId,
- schema: schema.length + " fields",
- });
- } catch (error) {
- logger.error("Error ensuring BigQuery table exists", {
- error,
- dataset: process.env.BIGQUERY_DATASET_ID,
- table: process.env.BIGQUERY_TABLE_ID || "firecrawl_jobs",
- });
- throw error;
- }
-}
-
-/**
- * Validates BigQuery configuration
- */
-function validateBigQueryConfig(): { valid: boolean; error?: string } {
- if (!bigquery) {
- return { valid: false, error: "BigQuery client not initialized" };
- }
-
- if (!process.env.BIGQUERY_DATASET_ID) {
- return { valid: false, error: "BIGQUERY_DATASET_ID not configured" };
- }
-
- if (!process.env.GOOGLE_CLOUD_PROJECT_ID && !process.env.GCS_CREDENTIALS) {
- return { valid: false, error: "Google Cloud credentials not configured" };
- }
-
- return { valid: true };
-}
-
-/**
- * Saves a job to BigQuery
- */
-export async function saveJobToBigQuery(
- job: FirecrawlJob,
- force: boolean = false
-): Promise<void> {
- const configValidation = validateBigQueryConfig();
- if (!configValidation.valid) {
- logger.debug("BigQuery not configured, skipping BigQuery logging", {
- reason: configValidation.error,
- });
- return;
- }
-
- const jobLogger = logger.child({
- module: "bigquery_jobs",
- method: "saveJobToBigQuery",
- ...createJobLoggerContext(job),
- });
-
- try {
- // Ensure table exists before attempting to insert
- // await ensureBigQueryTable();
-
- const datasetId = process.env.BIGQUERY_DATASET_ID;
- const tableId = process.env.BIGQUERY_TABLE_ID || "firecrawl_jobs";
- const table = bigquery.dataset(datasetId).table(tableId);
-
- const row = transformJobForBigQuery(job) as any;
-
- // Validate the row has required fields
- if (!row.timestamp) {
- row.timestamp = new Date().toISOString();
- }
-
- jobLogger.debug("Attempting to insert job to BigQuery", {
- dataset: datasetId,
- table: tableId,
- jobId: job.job_id,
- });
-
- if (force) {
- let i = 0;
- let done = false;
- while (i++ <= 10 && !done) {
- try {
- await table.insert([row], {
- ignoreUnknownValues: false,
- skipInvalidRows: false,
- });
- done = true;
- jobLogger.debug("Job logged to BigQuery successfully!");
- } catch (error) {
- jobLogger.error(
- "Failed to log job to BigQuery due to error -- trying again",
- {
- error: error.message || error,
- attempt: i,
- jobId: job.job_id,
- dataset: datasetId,
- table: tableId,
- }
- );
-
- // If it's a schema error, don't retry
- if (error.message && error.message.includes("schema")) {
- jobLogger.error("Schema error detected, stopping retries", { error: error.message });
- break;
- }
-
- await new Promise<void>((resolve) => setTimeout(() => resolve(), 100 * i));
- }
- }
- if (!done) {
- jobLogger.error("Failed to log job to BigQuery after all retries!");
- }
- } else {
- try {
- await table.insert([row], {
- ignoreUnknownValues: false,
- skipInvalidRows: false,
- });
- jobLogger.debug("Job logged to BigQuery successfully!");
- } catch (error) {
- jobLogger.error("Error logging job to BigQuery", {
- error: error.message || error,
- jobId: job.job_id,
- dataset: datasetId,
- table: tableId,
- });
- }
- }
- } catch (error) {
- jobLogger.error("Error saving job to BigQuery", {
- error: error.message || error,
- jobId: job.job_id,
- dataset: process.env.BIGQUERY_DATASET_ID,
- table: process.env.BIGQUERY_TABLE_ID || "firecrawl_jobs",
- });
- }
-}
-
-/**
- * Queries jobs from BigQuery
- */
-// export async function queryJobsFromBigQuery(
-// query: string,
-// params?: any[]
-// ): Promise<any[]> {
-// if (!bigquery || !process.env.BIGQUERY_DATASET_ID) {
-// logger.warn("BigQuery not configured");
-// return [];
-// }
-
-// try {
-// const options = {
-// query,
-// params,
-// location: process.env.BIGQUERY_LOCATION || "US",
-// };
-
-// const [rows] = await bigquery.query(options);
-// return rows;
-// } catch (error) {
-// logger.error("Error querying jobs from BigQuery", { error, query });
-// throw error;
-// }
-// }
diff --git a/apps/api/src/lib/deep-research/deep-research-service.ts b/apps/api/src/lib/deep-research/deep-research-service.ts
index 38d67ae56..d8e480cc1 100644
--- a/apps/api/src/lib/deep-research/deep-research-service.ts
+++ b/apps/api/src/lib/deep-research/deep-research-service.ts
@@ -2,7 +2,7 @@ import { logger as _logger } from "../logger";
import { updateDeepResearch } from "./deep-research-redis";
import { searchAndScrapeSearchResult } from "../../controllers/v1/search";
import { ResearchLLMService, ResearchStateManager } from "./research-manager";
-import { logJob } from "../../services/logging/log_job";
+import { logDeepResearch } from "../../services/logging/log_job";
import { billTeam } from "../../services/billing/credit_billing";
import { ExtractOptions } from "../../controllers/v1/types";
import { CostTracking } from "../cost-tracking";
@@ -151,6 +151,7 @@ export async function performDeepResearch(options: DeepResearchServiceOptions) {
proxy: "basic",
},
apiKeyId: apiKeyId,
+ requestId: researchId,
},
logger,
acuc?.flags ?? null,
@@ -402,29 +403,20 @@ export async function performDeepResearch(options: DeepResearchServiceOptions) {
const credits_billed = Math.min(urlsAnalyzed, options.maxUrls);
// Log job with token usage and sources
- await logJob({
- job_id: researchId,
- success: true,
- message: "Research completed",
- num_docs: 1,
- docs: [
- {
- finalAnalysis: finalAnalysis,
- sources: state.getSources(),
- json: finalAnalysisJson,
- },
- ],
- time_taken: (Date.now() - startTime) / 1000,
+ await logDeepResearch({
+ id: researchId,
+ request_id: researchId,
+ query: options.query,
team_id: teamId,
- mode: "deep-research",
- url: options.query,
- scrapeOptions: options,
- origin: "api",
- num_tokens: 0,
- tokens_billed: 0,
- cost_tracking: costTracking,
- credits_billed,
- zeroDataRetention: false, // not supported
+ options: options,
+ time_taken: (Date.now() - startTime) / 1000,
+ credits_cost: credits_billed,
+ cost_tracking: costTracking.toJSON(),
+ result: {
+ finalAnalysis: finalAnalysis,
+ sources: state.getSources(),
+ json: finalAnalysisJson,
+ },
});
await updateDeepResearch(researchId, {
status: "completed",
diff --git a/apps/api/src/lib/extract/document-scraper.ts b/apps/api/src/lib/extract/document-scraper.ts
index 72937a520..d5d702143 100644
--- a/apps/api/src/lib/extract/document-scraper.ts
+++ b/apps/api/src/lib/extract/document-scraper.ts
@@ -21,6 +21,7 @@ interface ScrapeDocumentOptions {
isSingleUrl?: boolean;
flags: TeamFlags | null;
apiKeyId: number | null;
+ requestId?: string;
}
export async function scrapeDocument(
@@ -69,6 +70,7 @@ export async function scrapeDocument(
startTime: Date.now(),
zeroDataRetention: false, // not supported
apiKeyId: options.apiKeyId,
+ requestId: options.requestId,
},
jobId,
jobPriority,
diff --git a/apps/api/src/lib/extract/extraction-service.ts b/apps/api/src/lib/extract/extraction-service.ts
index d59a68968..c2f377a9c 100644
--- a/apps/api/src/lib/extract/extraction-service.ts
+++ b/apps/api/src/lib/extract/extraction-service.ts
@@ -13,7 +13,7 @@ import {
generateSchemaFromPrompt,
} from "../../scraper/scrapeURL/transformers/llmExtract";
import { billTeam } from "../../services/billing/credit_billing";
-import { logJob } from "../../services/logging/log_job";
+import { logExtract } from "../../services/logging/log_job";
import { dereferenceSchema } from "./helpers/dereference-schema";
import { spreadSchemas } from "./helpers/spread-schemas";
import { transformArrayToObject } from "./helpers/transform-array-to-obj";
@@ -133,24 +133,17 @@ export async function performExtraction(
});
const tokens_billed = 300 + calculateThinkingCost(costTracking);
- logJob({
- job_id: extractId,
- success: false,
- message: "No search results found",
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed,
- sources,
- cost_tracking: costTracking,
- zeroDataRetention: false, // not supported
+ options: request,
+ model_kind: "fire-1",
+ credits_cost: Math.ceil(tokens_billed / 15),
+ is_successful: false,
+ error: "No search results found",
+ cost_tracking: costTracking.toJSON(),
});
await billTeam(
@@ -405,6 +398,7 @@ export async function performExtraction(
timeout,
flags: acuc?.flags ?? null,
apiKeyId,
+ requestId: extractId,
},
urlTraces,
logger.child({
@@ -676,27 +670,17 @@ export async function performExtraction(
multiEntitySchema: JSON.stringify(multiEntitySchema),
});
const tokens_billed = 300 + calculateThinkingCost(costTracking);
- logJob({
- job_id: extractId,
- success: false,
- message:
- error instanceof Error
- ? error.message
- : "Failed to transform array to object",
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed,
- sources,
- cost_tracking: costTracking,
- zeroDataRetention: false, // not supported
+ options: request,
+ model_kind: "fire-1",
+ credits_cost: Math.ceil(tokens_billed / 15),
+ is_successful: false,
+ error: "Failed to transform array to object",
+ cost_tracking: costTracking.toJSON(),
});
await billTeam(
teamId,
@@ -759,6 +743,7 @@ export async function performExtraction(
timeout,
flags: acuc?.flags ?? null,
apiKeyId,
+ requestId: extractId,
},
urlTraces,
logger.child({
@@ -796,24 +781,17 @@ export async function performExtraction(
logger.debug("Scrapes finished.", { docCount: validResults.length });
} catch (error) {
const tokens_billed = 300 + calculateThinkingCost(costTracking);
- logJob({
- job_id: extractId,
- success: false,
- message: error.message,
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed,
- sources,
- cost_tracking: costTracking,
- zeroDataRetention: false, // not supported
+ options: request,
+ credits_cost: Math.ceil(tokens_billed / 15),
+ is_successful: false,
+ error: "Failed to scrape documents",
+ model_kind: "fire-1",
+ cost_tracking: costTracking.toJSON(),
});
await billTeam(
teamId,
@@ -854,24 +832,17 @@ export async function performExtraction(
`Failed to bill team ${teamId} for thinking tokens: ${error}`,
);
});
- logJob({
- job_id: extractId,
- success: false,
- message: errorMessage,
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed,
- sources,
- cost_tracking: costTracking,
- zeroDataRetention: false, // not supported
+ options: request,
+ credits_cost: Math.ceil(tokens_billed / 15),
+ is_successful: false,
+ error: errorMessage,
+ model_kind: "fire-1",
+ cost_tracking: costTracking.toJSON(),
});
return {
success: false,
@@ -1048,24 +1019,17 @@ export async function performExtraction(
);
// Log job with token usage and sources
- logJob({
- job_id: extractId,
- success: true,
- message: "Extract completed",
- num_docs: 1,
- docs: finalResult ?? {},
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: totalTokensUsed,
- tokens_billed: tokensToBill,
- sources,
- cost_tracking: costTracking,
- zeroDataRetention: false, // not supported
+ options: request,
+ credits_cost: Math.ceil(tokensToBill / 15),
+ is_successful: true,
+ result: finalResult ?? {},
+ model_kind: "fire-1",
+ cost_tracking: costTracking.toJSON(),
}).then(() => {
updateExtract(extractId, {
status: "completed",
@@ -1121,29 +1085,18 @@ export async function performExtraction(
);
},
);
- await logJob({
- job_id: extractId,
- success: false,
- message:
- error instanceof Error
- ? error.message
- : typeof error === "string"
- ? error
- : "An unexpected error occurred",
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ await logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed,
- sources,
- cost_tracking: costTracking,
- zeroDataRetention: false, // not supported
+ options: request,
+ credits_cost: Math.ceil(tokens_billed / 15),
+ is_successful: false,
+ error:
+ error instanceof Error ? error.message : "An unexpected error occurred",
+ model_kind: "fire-1",
+ cost_tracking: costTracking.toJSON(),
});
throw error;
diff --git a/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts b/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
index 22f257e82..f6713bf0d 100644
--- a/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
+++ b/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
@@ -21,6 +21,7 @@ interface ScrapeDocumentOptions {
isSingleUrl?: boolean;
flags: TeamFlags | null;
apiKeyId: number | null;
+ requestId?: string;
}
export async function scrapeDocument_F0(
@@ -68,6 +69,7 @@ export async function scrapeDocument_F0(
startTime: Date.now(),
zeroDataRetention: false, // not supported
apiKeyId: options.apiKeyId,
+ requestId: options.requestId,
},
jobId,
jobPriority,
diff --git a/apps/api/src/lib/extract/fire-0/extraction-service-f0.ts b/apps/api/src/lib/extract/fire-0/extraction-service-f0.ts
index a4850d19a..63936aa32 100644
--- a/apps/api/src/lib/extract/fire-0/extraction-service-f0.ts
+++ b/apps/api/src/lib/extract/fire-0/extraction-service-f0.ts
@@ -7,7 +7,7 @@ import {
import { logger as _logger } from "../../logger";
import { scrapeDocument_F0 } from "./document-scraper-f0";
import { billTeam } from "../../../services/billing/credit_billing";
-import { logJob } from "../../../services/logging/log_job";
+import { logExtract } from "../../../services/logging/log_job";
import { spreadSchemas_F0 } from "./helpers/spread-schemas-f0";
import Ajv from "ajv";
const ajv = new Ajv();
@@ -35,6 +35,7 @@ import { mixSchemaObjects_F0 } from "./helpers/mix-schema-objs-f0";
import { singleAnswerCompletion_F0 } from "./completions/singleAnswer-f0";
import {
calculateFinalResultCost_F0,
+ estimateCost_F0,
estimateTotalCost_F0,
} from "./usage/llm-cost-f0";
import { SourceTracker_F0 } from "./helpers/source-tracker-f0";
@@ -119,23 +120,16 @@ export async function performExtraction_F0(
logger.error("No search results found", {
query: request.prompt,
});
- logJob({
- job_id: extractId,
- success: false,
- message: "No search results found",
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed: 0,
- sources,
- zeroDataRetention: false, // not supported
+ options: request,
+ model_kind: "fire-0",
+ credits_cost: 0,
+ is_successful: false,
+ error: "No search results found",
});
return {
success: false,
@@ -227,23 +221,16 @@ export async function performExtraction_F0(
logger.error("0 links! Bailing.", {
linkCount: links.length,
});
- logJob({
- job_id: extractId,
- success: false,
- message: "No valid URLs found to scrape",
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed: 0,
- sources,
- zeroDataRetention: false, // not supported
+ options: request,
+ credits_cost: 0,
+ is_successful: false,
+ error: "No valid URLs found to scrape",
+ model_kind: "fire-0",
});
return {
success: false,
@@ -370,6 +357,7 @@ export async function performExtraction_F0(
timeout,
flags: acuc?.flags ?? null,
apiKeyId,
+ requestId: extractId,
},
urlTraces,
logger.child({
@@ -606,23 +594,16 @@ export async function performExtraction_F0(
Object.assign(sources, multiEntitySources);
} catch (error) {
logger.error(`Failed to transform array to object`, { error });
- logJob({
- job_id: extractId,
- success: false,
- message: "Failed to transform array to object",
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed: 0,
- sources,
- zeroDataRetention: false, // not supported
+ options: request,
+ credits_cost: 0,
+ is_successful: false,
+ error: "Failed to transform array to object",
+ model_kind: "fire-0",
});
return {
success: false,
@@ -671,6 +652,7 @@ export async function performExtraction_F0(
timeout,
flags: acuc?.flags ?? null,
apiKeyId,
+ requestId: extractId,
},
urlTraces,
logger.child({
@@ -704,23 +686,16 @@ export async function performExtraction_F0(
logger.debug("Scrapes finished.", { docCount: validResults.length });
} catch (error) {
logger.error("Failed to scrape documents", { error });
- logJob({
- job_id: extractId,
- success: false,
- message: "Failed to scrape documents",
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed: 0,
- sources,
- zeroDataRetention: false, // not supported
+ options: request,
+ model_kind: "fire-0",
+ credits_cost: 0,
+ is_successful: false,
+ error: "Failed to scrape documents",
});
return {
success: false,
@@ -734,23 +709,16 @@ export async function performExtraction_F0(
if (docsMap.size == 0) {
// All urls are invalid
logger.error("All provided URLs are invalid!");
- logJob({
- job_id: extractId,
- success: false,
- message: "All provided URLs are invalid",
- num_docs: 1,
- docs: [],
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: 0,
- tokens_billed: 0,
- sources,
- zeroDataRetention: false, // not supported
+ options: request,
+ model_kind: "fire-0",
+ credits_cost: 0,
+ is_successful: false,
+ error: "All provided URLs are invalid",
});
return {
success: false,
@@ -906,23 +874,34 @@ export async function performExtraction_F0(
});
// Log job with token usage and sources
- logJob({
- job_id: extractId,
- success: true,
- message: "Extract completed",
- num_docs: 1,
- docs: finalResult ?? {},
- time_taken: (new Date().getTime() - createdAt.getTime()) / 1000,
+ logExtract({
+ id: extractId,
+ request_id: extractId,
+ urls: request.urls || [],
team_id: teamId,
- mode: "extract",
- url: request.urls?.join(", ") || "",
- scrapeOptions: request,
- origin: request.origin ?? "api",
- integration: request.integration,
- num_tokens: totalTokensUsed,
- tokens_billed: tokensToBill,
- sources,
- zeroDataRetention: false, // not supported
+ options: request,
+ model_kind: "fire-0",
+ credits_cost: Math.ceil(tokensToBill / 15),
+ is_successful: true,
+ result: finalResult ?? {},
+ cost_tracking: {
+ calls: tokenUsage.map(usage => ({
+ type: "other",
+ cost: estimateCost_F0(usage),
+ model: usage.model ?? "",
+ metadata: {},
+ stack: "",
+ tokens: {
+ input: usage.promptTokens,
+ output: usage.completionTokens,
+ },
+ })),
+ smartScrapeCallCount: 0,
+ smartScrapeCost: 0,
+ otherCallCount: tokenUsage.length,
+ otherCost: llmUsage,
+ totalCost: llmUsage,
+ },
}).then(() => {
updateExtract(extractId, {
status: "completed",
diff --git a/apps/api/src/lib/extract/fire-0/usage/llm-cost-f0.ts b/apps/api/src/lib/extract/fire-0/usage/llm-cost-f0.ts
index b41a021f5..ab6db63f6 100644
--- a/apps/api/src/lib/extract/fire-0/usage/llm-cost-f0.ts
+++ b/apps/api/src/lib/extract/fire-0/usage/llm-cost-f0.ts
@@ -23,7 +23,7 @@ export function estimateTotalCost_F0(tokenUsage: TokenUsage[]): number {
}, 0);
}
-function estimateCost_F0(tokenUsage: TokenUsage): number {
+export function estimateCost_F0(tokenUsage: TokenUsage): number {
let totalCost = 0;
try {
let model = tokenUsage.model ?? (process.env.MODEL_NAME || "gpt-4o-mini");
diff --git a/apps/api/src/lib/gcs-jobs.ts b/apps/api/src/lib/gcs-jobs.ts
index 672fb69df..62bdd0280 100644
--- a/apps/api/src/lib/gcs-jobs.ts
+++ b/apps/api/src/lib/gcs-jobs.ts
@@ -1,23 +1,30 @@
-import { FirecrawlJob } from "../types";
import { ApiError, Storage } from "@google-cloud/storage";
import { logger } from "./logger";
import { Document } from "../controllers/v1/types";
import { withSpan, setSpanAttributes } from "./otel-tracer";
+import type {
+ LoggedDeepResearch,
+ LoggedExtract,
+ LoggedLlmsTxt,
+ LoggedMap,
+ LoggedScrape,
+ LoggedSearch,
+} from "../services/logging/log_job";
const credentials = process.env.GCS_CREDENTIALS
? JSON.parse(atob(process.env.GCS_CREDENTIALS))
: undefined;
export const storage = new Storage({ credentials });
-export async function saveJobToGCS(job: FirecrawlJob): Promise<void> {
+export async function saveScrapeToGCS(scrape: LoggedScrape): Promise<void> {
return await withSpan("firecrawl-gcs-save-job", async span => {
setSpanAttributes(span, {
"gcs.operation": "save_job",
- "job.id": job.job_id,
- "job.team_id": job.team_id,
- "job.mode": job.mode,
- "job.success": job.success,
- "job.num_docs": job.num_docs,
+ "job.id": scrape.id,
+ "job.team_id": scrape.team_id,
+ "job.mode": "scrape",
+ "job.success": scrape.is_successful,
+ "job.num_docs": 1,
});
if (!process.env.GCS_BUCKET_NAME) {
@@ -26,12 +33,12 @@ export async function saveJobToGCS(job: FirecrawlJob): Promise<void> {
}
const bucket = storage.bucket(process.env.GCS_BUCKET_NAME);
- const blob = bucket.file(`${job.job_id}.json`);
+ const blob = bucket.file(`${scrape.id}.json`);
// Save job docs with retry
for (let i = 0; i < 3; i++) {
try {
- await blob.save(JSON.stringify(job.docs), {
+ await blob.save(JSON.stringify([scrape.doc]), {
contentType: "application/json",
});
break;
@@ -41,9 +48,10 @@ export async function saveJobToGCS(job: FirecrawlJob): Promise<void> {
} else {
logger.error(`Error saving job to GCS, retrying`, {
error,
- scrapeId: job.job_id,
- jobId: job.job_id,
+ scrapeId: scrape.id,
+ jobId: scrape.id,
i,
+ zeroDataRetention: scrape.zeroDataRetention,
});
}
}
@@ -54,25 +62,24 @@ export async function saveJobToGCS(job: FirecrawlJob): Promise<void> {
try {
await blob.setMetadata({
metadata: {
- job_id: job.job_id ?? null,
- success: job.success,
- message: job.message ?? null,
- num_docs: job.num_docs,
- time_taken: job.time_taken,
+ job_id: scrape.id ?? null,
+ success: scrape.is_successful,
+ message: scrape.zeroDataRetention ? null : (scrape.error ?? null),
+ num_docs: 1,
+ time_taken: scrape.time_taken,
team_id:
- job.team_id === "preview" || job.team_id?.startsWith("preview_")
+ scrape.team_id === "preview" ||
+ scrape.team_id?.startsWith("preview_")
? null
- : job.team_id,
- mode: job.mode,
- url: job.url,
- crawler_options: JSON.stringify(job.crawlerOptions),
- page_options: JSON.stringify(job.scrapeOptions),
- origin: job.origin,
- integration: job.integration ?? null,
- num_tokens: job.num_tokens ?? null,
- retry: !!job.retry,
- crawl_id: job.crawl_id ?? null,
- tokens_billed: job.tokens_billed ?? null,
+ : scrape.team_id,
+ mode: "scrape",
+ url: scrape.zeroDataRetention
+ ? "<redacted due to zero data retention>"
+ : scrape.url,
+ page_options: scrape.zeroDataRetention
+ ? null
+ : JSON.stringify(scrape.options),
+ request_id: scrape.request_id ?? null,
},
});
break;
@@ -80,11 +87,12 @@ export async function saveJobToGCS(job: FirecrawlJob): Promise<void> {
if (i === 2) {
throw error;
} else {
- logger.error(`Error saving job metadata to GCS, retrying`, {
+ logger.error(`Error saving scrape metadata to GCS, retrying`, {
error,
- scrapeId: job.job_id,
- jobId: job.job_id,
+ scrapeId: scrape.id,
+ jobId: scrape.id,
i,
+ zeroDataRetention: scrape.zeroDataRetention,
});
}
}
@@ -92,15 +100,390 @@ export async function saveJobToGCS(job: FirecrawlJob): Promise<void> {
setSpanAttributes(span, { "gcs.save_successful": true });
}).catch(error => {
- logger.error(`Error saving job to GCS`, {
+ logger.error(`Error saving scrape to GCS`, {
error,
- scrapeId: job.job_id,
- jobId: job.job_id,
+ scrapeId: scrape.id,
+ jobId: scrape.id,
+ zeroDataRetention: scrape.zeroDataRetention,
});
throw error;
});
}
+export async function saveSearchToGCS(search: LoggedSearch): Promise<void> {
+ return await withSpan("firecrawl-gcs-save-search", async span => {
+ setSpanAttributes(span, {
+ "gcs.operation": "save_search",
+ "search.id": search.id,
+ "search.team_id": search.team_id,
+ request_id: search.request_id,
+ });
+
+ if (!process.env.GCS_BUCKET_NAME) {
+ setSpanAttributes(span, { "gcs.bucket_configured": false });
+ return;
+ }
+
+ const bucket = storage.bucket(process.env.GCS_BUCKET_NAME);
+ const blob = bucket.file(`${search.id}.json`);
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.save(JSON.stringify(search.results), {
+ contentType: "application/json",
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving search to GCS, retrying`, {
+ error,
+ searchId: search.id,
+ i,
+ });
+ }
+ }
+ }
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.setMetadata({
+ metadata: {
+ mode: "search",
+ job_id: search.id,
+ num_docs: search.num_results,
+ time_taken: search.time_taken,
+ team_id:
+ search.team_id === "preview" ||
+ search.team_id?.startsWith("preview_")
+ ? null
+ : search.team_id,
+ query: search.zeroDataRetention
+ ? "<redacted due to zero data retention>"
+ : search.query,
+ options: search.zeroDataRetention
+ ? null
+ : JSON.stringify(search.options),
+ credits_cost: search.credits_cost,
+ success: search.is_successful,
+ error: search.zeroDataRetention ? null : (search.error ?? null),
+ num_results: search.num_results,
+ },
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving search metadata to GCS, retrying`, {
+ error,
+ searchId: search.id,
+ i,
+ });
+ }
+ }
+ }
+ });
+}
+
+export async function saveExtractToGCS(extract: LoggedExtract): Promise<void> {
+ return await withSpan("firecrawl-gcs-save-extract", async span => {
+ setSpanAttributes(span, {
+ "gcs.operation": "save_extract",
+ "extract.id": extract.id,
+ "extract.team_id": extract.team_id,
+ });
+
+ if (!process.env.GCS_BUCKET_NAME) {
+ setSpanAttributes(span, { "gcs.bucket_configured": false });
+ return;
+ }
+
+ const bucket = storage.bucket(process.env.GCS_BUCKET_NAME);
+ const blob = bucket.file(`${extract.id}.json`);
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.save(JSON.stringify(extract.result), {
+ contentType: "application/json",
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving extract to GCS, retrying`, {
+ error,
+ extractId: extract.id,
+ i,
+ });
+ }
+ }
+ }
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.setMetadata({
+ metadata: {
+ mode: "extract",
+ job_id: extract.id,
+ num_docs: 1,
+ team_id:
+ extract.team_id === "preview" ||
+ extract.team_id?.startsWith("preview_")
+ ? null
+ : extract.team_id,
+ options: JSON.stringify(extract.options),
+ credits_cost: extract.credits_cost,
+ success: extract.is_successful,
+ error: extract.error ?? null,
+ },
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving extract metadata to GCS, retrying`, {
+ error,
+ extractId: extract.id,
+ i,
+ });
+ }
+ }
+ }
+
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ return;
+ });
+}
+
+export async function saveMapToGCS(map: LoggedMap): Promise<void> {
+ return await withSpan("firecrawl-gcs-save-map", async span => {
+ setSpanAttributes(span, {
+ "gcs.operation": "save_map",
+ "map.id": map.id,
+ "map.team_id": map.team_id,
+ });
+
+ if (!process.env.GCS_BUCKET_NAME) {
+ setSpanAttributes(span, { "gcs.bucket_configured": false });
+ return;
+ }
+
+ const bucket = storage.bucket(process.env.GCS_BUCKET_NAME);
+ const blob = bucket.file(`${map.id}.json`);
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.save(JSON.stringify(map.results), {
+ contentType: "application/json",
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving map to GCS, retrying`, {
+ error,
+ mapId: map.id,
+ i,
+ });
+ }
+ }
+ }
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.setMetadata({
+ metadata: {
+ mode: "map",
+ job_id: map.id,
+ num_results: map.results.length,
+ team_id:
+ map.team_id === "preview" || map.team_id?.startsWith("preview_")
+ ? null
+ : map.team_id,
+ options: JSON.stringify(map.options),
+ credits_cost: map.credits_cost,
+ success: true,
+ },
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving map metadata to GCS, retrying`, {
+ error,
+ mapId: map.id,
+ i,
+ });
+ }
+ }
+ }
+
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ return;
+ });
+}
+
+export async function saveDeepResearchToGCS(
+ deepResearch: LoggedDeepResearch,
+): Promise<void> {
+ return await withSpan("firecrawl-gcs-save-deep-research", async span => {
+ setSpanAttributes(span, {
+ "gcs.operation": "save_deep_research",
+ "deep_research.id": deepResearch.id,
+ "deep_research.team_id": deepResearch.team_id,
+ });
+
+ if (!process.env.GCS_BUCKET_NAME) {
+ setSpanAttributes(span, { "gcs.bucket_configured": false });
+ return;
+ }
+
+ const bucket = storage.bucket(process.env.GCS_BUCKET_NAME);
+ const blob = bucket.file(`${deepResearch.id}.json`);
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.save(JSON.stringify(deepResearch.result), {
+ contentType: "application/json",
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving deep research to GCS, retrying`, {
+ error,
+ deepResearchId: deepResearch.id,
+ i,
+ });
+ }
+ }
+ }
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.setMetadata({
+ metadata: {
+ mode: "deep_research",
+ job_id: deepResearch.id,
+ team_id:
+ deepResearch.team_id === "preview" ||
+ deepResearch.team_id?.startsWith("preview_")
+ ? null
+ : deepResearch.team_id,
+ options: JSON.stringify(deepResearch.options),
+ credits_cost: deepResearch.credits_cost,
+ success: true,
+ time_taken: deepResearch.time_taken,
+ },
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving deep research metadata to GCS, retrying`, {
+ error,
+ deepResearchId: deepResearch.id,
+ i,
+ });
+ }
+ }
+ }
+
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ return;
+ });
+}
+
+export async function saveLlmsTxtToGCS(llmsTxt: LoggedLlmsTxt): Promise<void> {
+ return await withSpan("firecrawl-gcs-save-llms-txt", async span => {
+ setSpanAttributes(span, {
+ "gcs.operation": "save_llms_txt",
+ "llms_txt.id": llmsTxt.id,
+ "llms_txt.team_id": llmsTxt.team_id,
+ });
+
+ if (!process.env.GCS_BUCKET_NAME) {
+ setSpanAttributes(span, { "gcs.bucket_configured": false });
+ return;
+ }
+
+ const bucket = storage.bucket(process.env.GCS_BUCKET_NAME);
+ const blob = bucket.file(`${llmsTxt.id}.json`);
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.save(JSON.stringify(llmsTxt.result), {
+ contentType: "application/json",
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving llms txt to GCS, retrying`, {
+ error,
+ llmsTxtId: llmsTxt.id,
+ i,
+ });
+ }
+ }
+ }
+
+ for (let i = 0; i < 3; i++) {
+ try {
+ await blob.setMetadata({
+ metadata: {
+ mode: "llms_txt",
+ job_id: llmsTxt.id,
+ team_id:
+ llmsTxt.team_id === "preview" ||
+ llmsTxt.team_id?.startsWith("preview_")
+ ? null
+ : llmsTxt.team_id,
+ options: JSON.stringify(llmsTxt.options),
+ credits_cost: llmsTxt.credits_cost,
+ success: true,
+ num_urls: llmsTxt.num_urls,
+ cost_tracking: JSON.stringify(llmsTxt.cost_tracking),
+ },
+ });
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ break;
+ } catch (error) {
+ if (i === 2) {
+ throw error;
+ } else {
+ logger.error(`Error saving llms txt metadata to GCS, retrying`, {
+ error,
+ llmsTxtId: llmsTxt.id,
+ i,
+ });
+ }
+ }
+ }
+
+ setSpanAttributes(span, { "gcs.save_successful": true });
+ return;
+ });
+}
+
export async function getJobFromGCS(jobId: string): Promise<Document[] | null> {
return await withSpan("firecrawl-gcs-get-job", async span => {
setSpanAttributes(span, {
diff --git a/apps/api/src/lib/generate-llmstxt/generate-llmstxt-service.ts b/apps/api/src/lib/generate-llmstxt/generate-llmstxt-service.ts
index 92d681e90..c14bda01d 100644
--- a/apps/api/src/lib/generate-llmstxt/generate-llmstxt-service.ts
+++ b/apps/api/src/lib/generate-llmstxt/generate-llmstxt-service.ts
@@ -8,7 +8,7 @@ import {
saveLlmsTextToCache,
} from "./generate-llmstxt-supabase";
import { billTeam } from "../../services/billing/credit_billing";
-import { logJob } from "../../services/logging/log_job";
+import { logLlmsTxt } from "../../services/logging/log_job";
import { getModel } from "../generic-ai";
import { generateCompletions } from "../../scraper/scrapeURL/transformers/llmExtract";
import { CostTracking } from "../cost-tracking";
@@ -166,6 +166,7 @@ export async function performGenerateLlmsTxt(
isSingleUrl: true,
flags: acuc?.flags ?? null,
apiKeyId,
+ requestId: generationId,
},
[],
logger,
@@ -249,24 +250,20 @@ export async function performGenerateLlmsTxt(
});
// Log job with token usage and sources
- await logJob({
- job_id: generationId,
- success: true,
- message: "LLMs text generation completed",
- num_docs: urls.length,
- docs: [{ llmstxt: llmstxt, llmsfulltxt: llmsFulltxt }],
- time_taken: (Date.now() - startTime) / 1000,
+ await logLlmsTxt({
+ id: generationId,
+ request_id: generationId,
+ url,
team_id: teamId,
- mode: "llmstxt",
- url: url,
- scrapeOptions: options,
- origin: "api",
- num_tokens: 0,
- tokens_billed: 0,
- sources: {},
- cost_tracking: costTracking,
- credits_billed: urls.length,
- zeroDataRetention: false,
+ options: {
+ maxUrls: maxUrls,
+ showFullText: showFullText,
+ cache: cache,
+ },
+ num_urls: urls.length,
+ cost_tracking: costTracking.toJSON(),
+ credits_cost: urls.length,
+ result: { llmstxt, llmsfulltxt: llmsFulltxt },
});
// Bill team for usage
diff --git a/apps/api/src/lib/job-transform.ts b/apps/api/src/lib/job-transform.ts
deleted file mode 100644
index fac5a8f02..000000000
--- a/apps/api/src/lib/job-transform.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { FirecrawlJob } from "../types";
-
-function cleanOfNull<T>(x: T): T {
- if (Array.isArray(x)) {
- return x.map(x => cleanOfNull(x)) as T;
- } else if (typeof x === "object" && x !== null) {
- return Object.fromEntries(
- Object.entries(x).map(([k, v]) => [k, cleanOfNull(v)]),
- ) as T;
- } else if (typeof x === "string") {
- return x.replaceAll("\u0000", "") as T;
- } else {
- return x;
- }
-}
-
-interface TransformOptions {
- /** Whether to include timestamp field (for BigQuery) */
- includeTimestamp?: boolean;
- /** Whether to serialize objects to JSON strings (for BigQuery) */
- serializeObjects?: boolean;
- /** Whether to clean null values from docs */
- cleanNullValues?: boolean;
-}
-
-/**
- * Transforms a FirecrawlJob into a standardized format for logging/storage
- */
-export function transformJobForLogging(
- job: FirecrawlJob,
- options: TransformOptions = {},
-) {
- const {
- includeTimestamp = false,
- serializeObjects = false,
- cleanNullValues = true,
- } = options;
-
- const zeroDataRetention = job.zeroDataRetention ?? false;
-
- // Determine if docs should be included based on zero data retention and GCS usage
- const shouldIncludeDocs =
- !zeroDataRetention &&
- !(
- (job.mode === "single_urls" || job.mode === "scrape") &&
- process.env.GCS_BUCKET_NAME
- );
-
- const baseTransform = {
- job_id: job.job_id ? job.job_id : null,
- success: job.success,
- message: zeroDataRetention ? null : job.message,
- num_docs: job.num_docs,
- docs: shouldIncludeDocs
- ? cleanNullValues
- ? cleanOfNull(job.docs)
- : job.docs
- : null,
- time_taken: job.time_taken,
- team_id:
- job.team_id === "preview" || job.team_id?.startsWith("preview_")
- ? null
- : job.team_id,
- mode: job.mode,
- url: zeroDataRetention ? "<redacted due to zero data retention>" : job.url,
- crawler_options: zeroDataRetention ? null : job.crawlerOptions,
- page_options: zeroDataRetention ? null : job.scrapeOptions,
- origin: zeroDataRetention ? null : job.origin,
- integration: zeroDataRetention ? null : (job.integration ?? null),
- num_tokens: job.num_tokens,
- retry: !!job.retry,
- crawl_id: job.crawl_id,
- tokens_billed: job.tokens_billed,
- is_migrated: true,
- cost_tracking: zeroDataRetention ? null : job.cost_tracking,
- pdf_num_pages: zeroDataRetention ? null : (job.pdf_num_pages ?? null),
- credits_billed: job.credits_billed ?? null,
- change_tracking_tag: zeroDataRetention
- ? null
- : (job.change_tracking_tag ?? null),
- dr_clean_by:
- zeroDataRetention && job.crawl_id
- ? new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString()
- : null,
- };
-
- // Add timestamp if requested (for BigQuery)
- const withTimestamp = includeTimestamp
- ? { ...baseTransform, timestamp: new Date().toISOString() }
- : baseTransform;
-
- // Serialize objects to JSON strings if requested (for BigQuery)
- if (serializeObjects) {
- return {
- ...withTimestamp,
- docs: withTimestamp.docs ? JSON.stringify(withTimestamp.docs) : null,
- crawler_options: withTimestamp.crawler_options
- ? JSON.stringify(withTimestamp.crawler_options)
- : null,
- page_options: withTimestamp.page_options
- ? JSON.stringify(withTimestamp.page_options)
- : null,
- cost_tracking: withTimestamp.cost_tracking
- ? JSON.stringify(withTimestamp.cost_tracking)
- : null,
- };
- }
-
- return withTimestamp;
-}
-
-/**
- * Creates logger context based on job mode and ID
- */
-export function createJobLoggerContext(job: FirecrawlJob) {
- return {
- ...(job.mode === "scrape" ||
- job.mode === "single_urls" ||
- job.mode === "single_url"
- ? {
- scrapeId: job.job_id,
- }
- : {}),
- ...(job.mode === "crawl" || job.mode === "batch_scrape"
- ? {
- crawlId: job.job_id,
- }
- : {}),
- ...(job.mode === "extract"
- ? {
- extractId: job.job_id,
- }
- : {}),
- };
-}
diff --git a/apps/api/src/lib/map-utils.ts b/apps/api/src/lib/map-utils.ts
index 5f479a0e3..a66d09c06 100644
--- a/apps/api/src/lib/map-utils.ts
+++ b/apps/api/src/lib/map-utils.ts
@@ -92,6 +92,7 @@ export async function getMapResults({
useIndex = true,
location,
maxFireEngineResults = MAX_FIRE_ENGINE_RESULTS,
+ id: providedId,
}: {
url: string;
search?: string;
@@ -109,6 +110,7 @@ export async function getMapResults({
useIndex?: boolean;
location?: ScrapeOptions["location"];
maxFireEngineResults?: number;
+ id?: string;
}): Promise<MapResult> {
const functionStartTime = Date.now();
@@ -122,7 +124,7 @@ export async function getMapResults({
url = urlObj.toString();
}
- const id = uuidv7();
+ const id = providedId ?? uuidv7();
let mapResults: MapDocument[] = [];
const zeroDataRetention = flags?.forceZDR ?? false;
diff --git a/apps/api/src/lib/supabase-jobs.ts b/apps/api/src/lib/supabase-jobs.ts
index 41ef30e8d..db7071cbe 100644
--- a/apps/api/src/lib/supabase-jobs.ts
+++ b/apps/api/src/lib/supabase-jobs.ts
@@ -3,34 +3,20 @@ import { supabase_rr_service, supabase_service } from "../services/supabase";
import { logger } from "./logger";
import * as Sentry from "@sentry/node";
+// ============================================================================
+// NEW TABLES: scrapes, requests, crawls, etc.
+// ============================================================================
+
/**
- * Get a single firecrawl_job by ID
- * @param jobId ID of Job
- * @returns {any | null} Job
+ * Get a single scrape by ID from the new scrapes table
+ * @param scrapeId ID of Scrape
+ * @returns Scrape data or null
*/
-export const supabaseGetJobById = async (jobId: string) => {
+export const supabaseGetScrapeById = async (scrapeId: string) => {
const { data, error } = await supabase_rr_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select("*")
- .eq("job_id", jobId)
- .single();
-
- if (error) {
- return null;
- }
-
- if (!data) {
- return null;
- }
-
- return data;
-};
-
-export const supabaseGetJobByIdDirect = async (jobId: string) => {
- const { data, error } = await supabase_service
- .from("firecrawl_jobs")
- .select("*")
- .eq("job_id", jobId)
+ .eq("id", scrapeId)
.single();
if (error) {
@@ -45,18 +31,18 @@ export const supabaseGetJobByIdDirect = async (jobId: string) => {
};
/**
- * Get multiple firecrawl_jobs by ID. Use this if you're not requesting a lot (50+) of jobs at once.
- * @param jobIds IDs of Jobs
- * @returns {any[]} Jobs
+ * Get multiple scrapes by ID from the new scrapes table
+ * @param scrapeIds IDs of Scrapes
+ * @returns Scrape data array
*/
-export const supabaseGetJobsById = async (jobIds: string[]) => {
+export const supabaseGetScrapesById = async (scrapeIds: string[]) => {
const { data, error } = await supabase_rr_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select()
- .in("job_id", jobIds);
+ .in("id", scrapeIds);
if (error) {
- logger.error(`Error in supabaseGetJobsById: ${error}`);
+ logger.error(`Error in supabaseGetScrapesById: ${error}`);
Sentry.captureException(error);
return [];
}
@@ -69,18 +55,18 @@ export const supabaseGetJobsById = async (jobIds: string[]) => {
};
/**
- * Get multiple firecrawl_jobs by crawl ID. Use this if you need a lot of jobs at once.
- * @param crawlId ID of crawl
- * @returns {any[]} Jobs
+ * Get multiple scrapes by request ID (crawl/batch scrape ID) from the new scrapes table
+ * @param requestId ID of the parent request (crawl or batch scrape)
+ * @returns Scrape data array
*/
-export const supabaseGetJobsByCrawlId = async (crawlId: string) => {
+export const supabaseGetScrapesByRequestId = async (requestId: string) => {
const { data, error } = await supabase_rr_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select()
- .eq("crawl_id", crawlId);
+ .eq("request_id", requestId);
if (error) {
- logger.error(`Error in supabaseGetJobsByCrawlId: ${error}`);
+ logger.error(`Error in supabaseGetScrapesByRequestId: ${error}`);
Sentry.captureException(error);
return [];
}
@@ -92,19 +78,25 @@ export const supabaseGetJobsByCrawlId = async (crawlId: string) => {
return data;
};
-export const supabaseGetJobByIdOnlyData = async (
- jobId: string,
+/**
+ * Get only team_id from a scrape by ID (lightweight query)
+ * @param scrapeId ID of Scrape
+ * @param logger Optional logger for error reporting
+ * @returns Object with team_id or null
+ */
+export const supabaseGetScrapeByIdOnlyData = async (
+ scrapeId: string,
logger?: Logger,
) => {
const { data, error } = await supabase_rr_service
- .from("firecrawl_jobs")
+ .from("scrapes")
.select("team_id")
- .eq("job_id", jobId)
+ .eq("id", scrapeId)
.single();
if (error) {
if (logger) {
- logger.error("Error in supabaseGetJobByIdOnlyData", { error });
+ logger.error("Error in supabaseGetScrapeByIdOnlyData", { error });
}
return null;
}
@@ -115,3 +107,21 @@ export const supabaseGetJobByIdOnlyData = async (
return data;
};
+
+export const supabaseGetExtractByIdDirect = async (extractId: string) => {
+ const { data, error } = await supabase_service
+ .from("extracts")
+ .select("*")
+ .eq("id", extractId)
+ .single();
+
+ if (error) {
+ return null;
+ }
+
+ if (!data) {
+ return null;
+ }
+
+ return data;
+};
diff --git a/apps/api/src/routes/admin.ts b/apps/api/src/routes/admin.ts
index 9ec91598c..f4f8f9b7d 100644
--- a/apps/api/src/routes/admin.ts
+++ b/apps/api/src/routes/admin.ts
@@ -1,6 +1,6 @@
import express from "express";
import { redisHealthController } from "../controllers/v0/admin/redis-health";
-import { authMiddleware, blocklistMiddleware, wrap } from "./shared";
+import { wrap } from "./shared";
import { acucCacheClearController } from "../controllers/v0/admin/acuc-cache-clear";
import { checkFireEngine } from "../controllers/v0/admin/check-fire-engine";
import { cclogController } from "../controllers/v0/admin/cclog";
@@ -11,11 +11,11 @@ import {
metricsController,
nuqMetricsController,
} from "../controllers/v0/admin/metrics";
-import { crawlCheckController } from "../controllers/v0/admin/crawl-check";
import { realtimeSearchController } from "../controllers/v2/f-search";
import { concurrencyQueueBackfillController } from "../controllers/v0/admin/concurrency-queue-backfill";
import { integCreateUserController } from "../controllers/v0/admin/create-user";
import { integValidateApiKeyController } from "../controllers/v0/admin/validate-api-key";
+import { crawlMigrationController } from "../controllers/v0/admin/crawl-migration";
export const adminRouter = express.Router();
@@ -64,11 +64,6 @@ adminRouter.get(
wrap(nuqMetricsController),
);
-adminRouter.get(
- `/admin/${process.env.BULL_AUTH_KEY}/crawl-check`,
- wrap(crawlCheckController),
-);
-
adminRouter.post(
`/admin/${process.env.BULL_AUTH_KEY}/fsearch`,
wrap(realtimeSearchController),
@@ -88,3 +83,8 @@ adminRouter.post(
`/admin/integration/validate-api-key`,
wrap(integValidateApiKeyController),
);
+
+adminRouter.post(
+ `/admin/${process.env.BULL_AUTH_KEY}/crawl-migration`,
+ wrap(crawlMigrationController),
+);
diff --git a/apps/api/src/scraper/scrapeURL/engines/utils/downloadFile.ts b/apps/api/src/scraper/scrapeURL/engines/utils/downloadFile.ts
index ca6c6d37a..704fd0097 100644
--- a/apps/api/src/scraper/scrapeURL/engines/utils/downloadFile.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/utils/downloadFile.ts
@@ -9,7 +9,7 @@ import {
SSLError,
} from "../../error";
import { Writable } from "stream";
-import { v4 as uuid } from "uuid";
+import { v7 as uuid } from "uuid";
import * as undici from "undici";
import { getSecureDispatcher } from "./safeFetch";
import { logger } from "../../../../lib/logger";
diff --git a/apps/api/src/services/indexing/index-worker.ts b/apps/api/src/services/indexing/index-worker.ts
index 7478bb0fe..b0209899f 100644
--- a/apps/api/src/services/indexing/index-worker.ts
+++ b/apps/api/src/services/indexing/index-worker.ts
@@ -510,7 +510,7 @@ const processPrecrawlJob = async (token: string, job: Job) => {
zeroDataRetention: false,
apiKeyId: null,
},
- crypto.randomUUID(),
+ uuidv7(),
);
submittedCrawls++;
diff --git a/apps/api/src/services/logging/log_job.ts b/apps/api/src/services/logging/log_job.ts
index 9a858e7c6..0515e37b7 100644
--- a/apps/api/src/services/logging/log_job.ts
+++ b/apps/api/src/services/logging/log_job.ts
@@ -1,279 +1,572 @@
import { supabase_service } from "../supabase";
-import { FirecrawlJob } from "../../types";
-import { posthog } from "../posthog";
import "dotenv/config";
import { logger as _logger } from "../../lib/logger";
import { configDotenv } from "dotenv";
-import { saveJobToGCS } from "../../lib/gcs-jobs";
-import { saveJobToBigQuery } from "../../lib/bigquery-jobs";
import {
- transformJobForLogging,
- createJobLoggerContext,
-} from "../../lib/job-transform";
-import { withSpan, setSpanAttributes } from "../../lib/otel-tracer";
+ saveDeepResearchToGCS,
+ saveExtractToGCS,
+ saveLlmsTxtToGCS,
+ saveMapToGCS,
+ saveScrapeToGCS,
+ saveSearchToGCS,
+} from "../../lib/gcs-jobs";
import { hasFormatOfType } from "../../lib/format-utils";
+import type { Document, ScrapeOptions } from "../../controllers/v2/types";
+import type { CostTracking } from "../../lib/cost-tracking";
+import type { Logger } from "winston";
configDotenv();
-export async function logJob(
- job: FirecrawlJob,
- force: boolean = false,
- bypassLogging: boolean = false,
+const previewTeamId = "3adefd26-77ec-5968-8dcf-c94b5630d1de";
+
+async function robustInsert(
+ table: string,
+ data: any,
+ force: boolean,
+ logger: Logger,
) {
- const useDbAuthentication = process.env.USE_DB_AUTHENTICATION === "true";
- if (!useDbAuthentication) {
+ if (process.env.USE_DB_AUTHENTICATION !== "true") {
+ logger.info(
+ "Skipping database insertion due to USE_DB_AUTHENTICATION being off",
+ { table },
+ );
return;
}
- let logger = _logger.child({
- module: "log_job",
- method: "logJob",
- ...createJobLoggerContext(job),
- });
-
- const zeroDataRetention = job.zeroDataRetention ?? false;
-
- logger = logger.child({
- zeroDataRetention,
- });
+ if (force) {
+ let i = 0,
+ done = false;
+ while (i++ <= 10) {
+ try {
+ const { error } = await supabase_service.from(table).insert(data);
+ if (error) {
+ logger.error(
+ "Error inserting into database due to Supabase error, trying again",
+ { error, table },
+ );
+ await new Promise(resolve => setTimeout(resolve, 75));
+ } else {
+ done = true;
+ break;
+ }
+ } catch (error) {
+ logger.error(
+ "Error inserting into database due to unknown error, trying again",
+ { error, table },
+ );
+ await new Promise(resolve => setTimeout(resolve, 75));
+ }
+ }
- try {
- // Save to GCS if configured
- if (process.env.GCS_BUCKET_NAME) {
- await withSpan("firecrawl-log-job-save-to-gcs", async span => {
- setSpanAttributes(span, {
- "log_job.operation": "save_to_gcs",
- "job.id": job.job_id,
- "job.team_id": job.team_id,
- });
- await saveJobToGCS(job);
+ if (done) {
+ logger.info("Inserted into database successfully", { table });
+ } else {
+ logger.error("Failed to insert into database after 10 attempts", {
+ table,
});
}
-
- // Save to BigQuery if configured
- if (process.env.BIGQUERY_DATASET_ID) {
- withSpan("firecrawl-log-job-save-to-bigquery", async span => {
- setSpanAttributes(span, {
- "log_job.operation": "save_to_bigquery",
- "job.id": job.job_id,
- "job.team_id": job.team_id,
- "job.force": force,
+ } else {
+ try {
+ const { error } = await supabase_service.from(table).insert(data);
+ if (error) {
+ logger.error("Error inserting into database due to Supabase error", {
+ error,
+ table,
});
- await saveJobToBigQuery(job, force);
- }).catch(error => {
- logger.error("Error saving job to BigQuery", { error });
+ } else {
+ logger.info("Inserted into database successfully", { table });
+ }
+ } catch (error) {
+ logger.error("Error inserting into database due to unknown error", {
+ error,
+ table,
});
}
+ }
+}
- // Redact any pages that have an authorization header
- // actually, Don't. we use the db to retrieve results now. this breaks authed crawls - mogery
- // if (
- // job.scrapeOptions &&
- // job.scrapeOptions.headers &&
- // job.scrapeOptions.headers["Authorization"]
- // ) {
- // job.scrapeOptions.headers["Authorization"] = "REDACTED";
- // job.docs = [
- // {
- // content: "REDACTED DUE TO AUTHORIZATION HEADER",
- // html: "REDACTED DUE TO AUTHORIZATION HEADER",
- // },
- // ];
- // }
- const jobColumn = transformJobForLogging(job, {
- includeTimestamp: false,
- serializeObjects: false,
- cleanNullValues: true,
- });
-
- if (bypassLogging) {
- return;
- }
+type LoggedRequest = {
+ id: string;
+ kind:
+ | "scrape"
+ | "crawl"
+ | "batch_scrape"
+ | "search"
+ | "extract"
+ | "llmstxt"
+ | "deep_research"
+ | "map";
+ api_version: string;
+ team_id: string;
+ origin?: string;
+ integration?: string | null;
+ target_hint: string;
+ zeroDataRetention: boolean;
+};
- if (force) {
- await withSpan("firecrawl-log-job-supabase-force-insert", async span => {
- setSpanAttributes(span, {
- "log_job.operation": "supabase_force_insert",
- "job.id": job.job_id,
- "job.team_id": job.team_id,
- "job.force": true,
- });
+export async function logRequest(request: LoggedRequest) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logRequest",
+ requestId: request.id,
+ teamId: request.team_id,
+ zeroDataRetention: request.zeroDataRetention,
+ });
- let i = 0,
- done = false;
- while (i++ <= 10) {
- try {
- const { error } = await supabase_service
- .from("firecrawl_jobs")
- .insert([jobColumn]);
- if (error) {
- logger.error(
- "Failed to log job due to Supabase error -- trying again",
- { error },
- );
- await new Promise<void>(resolve =>
- setTimeout(() => resolve(), 75),
- );
- } else {
- done = true;
- break;
- }
- } catch (error) {
- logger.error(
- "Failed to log job due to thrown error -- trying again",
- { error },
- );
- await new Promise<void>(resolve => setTimeout(() => resolve(), 75));
- }
- }
+ await robustInsert(
+ "requests",
+ {
+ id: request.id,
+ kind: request.kind,
+ api_version: request.api_version,
+ team_id:
+ request.team_id === "preview" || request.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : request.team_id,
+ origin: request.origin,
+ integration: request.integration ?? null,
+ target_hint: request.zeroDataRetention
+ ? "<redacted due to zero data retention>"
+ : request.target_hint,
+ dr_clean_by: request.zeroDataRetention
+ ? new Date(Date.now() + 24 * 60 * 60 * 1000)
+ : null,
+ },
+ true,
+ logger,
+ );
+}
- setSpanAttributes(span, { "supabase.insert_successful": done });
- if (done) {
- logger.debug("Job logged successfully!");
- } else {
- logger.error("Failed to log job!");
- }
- });
- } else {
- await withSpan("firecrawl-log-job-supabase-insert", async span => {
- setSpanAttributes(span, {
- "log_job.operation": "supabase_insert",
- "job.id": job.job_id,
- "job.team_id": job.team_id,
- "job.force": false,
- });
+export type LoggedScrape = {
+ id: string;
+ request_id: string;
+ url: string;
+ is_successful: boolean;
+ error?: string;
+ doc?: Document;
+ time_taken: number;
+ team_id: string;
+ options: ScrapeOptions;
+ cost_tracking?: ReturnType<typeof CostTracking.prototype.toJSON>;
+ pdf_num_pages?: number;
+ credits_cost: number;
+ skipNuq: boolean;
+ zeroDataRetention: boolean;
+};
- const { error } = await supabase_service
- .from("firecrawl_jobs")
- .insert([jobColumn]);
+export async function logScrape(scrape: LoggedScrape, force: boolean = false) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logScrape",
+ scrapeId: scrape.id,
+ requestId: scrape.request_id,
+ teamId: scrape.team_id,
+ zeroDataRetention: scrape.zeroDataRetention,
+ });
- if (error) {
- setSpanAttributes(span, { "supabase.insert_successful": false });
- logger.error(`Error logging job`, {
- error,
- });
- throw error;
- } else {
- setSpanAttributes(span, { "supabase.insert_successful": true });
- logger.debug("Job logged successfully!");
- }
- });
- }
+ await robustInsert(
+ "scrapes",
+ {
+ id: scrape.id,
+ request_id: scrape.request_id,
+ url: scrape.zeroDataRetention
+ ? "<redacted due to zero data retention>"
+ : scrape.url,
+ is_successful: scrape.is_successful,
+ error: scrape.error ?? null,
+ time_taken: scrape.time_taken,
+ team_id:
+ scrape.team_id === "preview" || scrape.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : scrape.team_id,
+ options: scrape.zeroDataRetention ? null : scrape.options,
+ cost_tracking: scrape.zeroDataRetention
+ ? null
+ : (scrape.cost_tracking ?? null),
+ pdf_num_pages: scrape.zeroDataRetention
+ ? null
+ : (scrape.pdf_num_pages ?? null),
+ credits_cost: scrape.credits_cost,
+ },
+ force,
+ logger,
+ );
- // Insert into change_tracking_scrapes table if conditions are met
- if (
- job.success &&
- (job.mode === "scrape" || job.mode === "single_urls") &&
- job.url &&
- !zeroDataRetention
- ) {
- const hasMarkdown = hasFormatOfType(
- job.scrapeOptions?.formats,
- "markdown",
- );
- const hasChangeTracking = hasFormatOfType(
- job.scrapeOptions?.formats,
- "changeTracking",
+ if (
+ scrape.doc &&
+ process.env.GCS_BUCKET_NAME &&
+ !(scrape.skipNuq && scrape.zeroDataRetention)
+ ) {
+ await saveScrapeToGCS(scrape);
+ }
+
+ if (
+ scrape.is_successful &&
+ !scrape.zeroDataRetention &&
+ process.env.USE_DB_AUTHENTICATION === "true"
+ ) {
+ const hasMarkdown = hasFormatOfType(scrape.options.formats, "markdown");
+ const hasChangeTracking = hasFormatOfType(
+ scrape.options.formats,
+ "changeTracking",
+ );
+
+ if (hasMarkdown || hasChangeTracking) {
+ const { error } = await supabase_service.rpc(
+ "change_tracking_insert_scrape",
+ {
+ p_team_id: scrape.team_id,
+ p_url: scrape.url,
+ p_job_id: scrape.id,
+ p_change_tracking_tag: hasChangeTracking
+ ? hasChangeTracking.tag
+ : null,
+ p_date_added: new Date().toISOString(),
+ },
);
- // Insert if markdown format exists (either standalone or as part of change tracking)
- if (hasMarkdown || hasChangeTracking) {
- await withSpan(
- "firecrawl-log-job-change-tracking-insert",
- async span => {
- setSpanAttributes(span, {
- "log_job.operation": "change_tracking_insert",
- "job.id": job.job_id,
- "job.team_id": job.team_id,
- "job.url": job.url,
- "job.change_tracking_tag": job.change_tracking_tag ?? undefined,
- });
-
- try {
- const { error } = await supabase_service.rpc(
- "change_tracking_insert_scrape",
- {
- p_team_id: job.team_id,
- p_url: job.url,
- p_job_id: job.job_id,
- p_change_tracking_tag: job.change_tracking_tag ?? null,
- p_date_added: new Date().toISOString(),
- },
- );
-
- if (error) {
- setSpanAttributes(span, {
- "change_tracking.insert_successful": false,
- });
- logger.warn("Error inserting into change_tracking_scrapes", {
- error,
- jobId: job.job_id,
- });
- } else {
- setSpanAttributes(span, {
- "change_tracking.insert_successful": true,
- });
- logger.debug("Change tracking record inserted successfully!");
- }
- } catch (error) {
- setSpanAttributes(span, {
- "change_tracking.insert_successful": false,
- });
- logger.warn(
- "Exception while inserting into change_tracking_scrapes",
- {
- error,
- jobId: job.job_id,
- },
- );
- }
- },
- );
+ if (error) {
+ _logger.warn("Error inserting into change_tracking_scrapes", {
+ error,
+ scrapeId: scrape.id,
+ teamId: scrape.team_id,
+ });
+ } else {
+ _logger.debug("Change tracking record inserted successfully");
}
}
+ }
+}
+
+type LoggedCrawl = {
+ id: string;
+ request_id: string;
+ url: string;
+ team_id: string;
+ options: any;
+ num_docs: number;
+ credits_cost: number;
+ zeroDataRetention: boolean;
+ cancelled: boolean;
+};
+
+export async function logCrawl(crawl: LoggedCrawl, force: boolean = false) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logCrawl",
+ crawlId: crawl.id,
+ requestId: crawl.request_id,
+ teamId: crawl.team_id,
+ zeroDataRetention: crawl.zeroDataRetention,
+ });
+
+ await robustInsert(
+ "crawls",
+ {
+ id: crawl.id,
+ request_id: crawl.request_id,
+ url: crawl.zeroDataRetention
+ ? "<redacted due to zero data retention>"
+ : crawl.url,
+ team_id:
+ crawl.team_id === "preview" || crawl.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : crawl.team_id,
+ options: crawl.zeroDataRetention ? null : crawl.options,
+ num_docs: crawl.num_docs,
+ credits_cost: crawl.credits_cost,
+ cancelled: crawl.cancelled,
+ },
+ force,
+ logger,
+ );
+}
+
+type LoggedBatchScrape = {
+ id: string;
+ request_id: string;
+ team_id: string;
+ num_docs: number;
+ credits_cost: number;
+ zeroDataRetention: boolean;
+ cancelled: boolean;
+};
+
+export async function logBatchScrape(
+ batchScrape: LoggedBatchScrape,
+ force: boolean = false,
+) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logBatchScrape",
+ batchScrapeId: batchScrape.id,
+ requestId: batchScrape.request_id,
+ teamId: batchScrape.team_id,
+ zeroDataRetention: batchScrape.zeroDataRetention,
+ });
+
+ await robustInsert(
+ "batch_scrapes",
+ {
+ id: batchScrape.id,
+ request_id: batchScrape.request_id,
+ team_id:
+ batchScrape.team_id === "preview" ||
+ batchScrape.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : batchScrape.team_id,
+ num_docs: batchScrape.num_docs,
+ credits_cost: batchScrape.credits_cost,
+ cancelled: batchScrape.cancelled,
+ },
+ force,
+ logger,
+ );
+}
+
+export type LoggedSearch = {
+ id: string;
+ request_id: string;
+ query: string;
+ team_id: string;
+ options: any;
+ time_taken: number;
+ credits_cost: number;
+ is_successful: boolean;
+ error?: string;
+ num_results: number;
+ results: any;
+ zeroDataRetention: boolean;
+};
+
+export async function logSearch(search: LoggedSearch, force: boolean = false) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logSearch",
+ searchId: search.id,
+ requestId: search.request_id,
+ teamId: search.team_id,
+ zeroDataRetention: search.zeroDataRetention,
+ });
+
+ await robustInsert(
+ "searches",
+ {
+ id: search.id,
+ request_id: search.request_id,
+ query: search.zeroDataRetention
+ ? "<redacted due to zero data retention>"
+ : search.query,
+ team_id:
+ search.team_id === "preview" || search.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : search.team_id,
+ options: search.zeroDataRetention ? null : search.options,
+ credits_cost: search.credits_cost,
+ is_successful: search.is_successful,
+ error: search.zeroDataRetention ? null : (search.error ?? null),
+ num_results: search.num_results,
+ time_taken: search.time_taken,
+ },
+ force,
+ logger,
+ );
+
+ if (search.results && !search.zeroDataRetention) {
+ await saveSearchToGCS(search);
+ }
+}
+
+export type LoggedExtract = {
+ id: string;
+ request_id: string;
+ urls: string[];
+ team_id: string;
+ options: any;
+ model_kind: "fire-0" | "fire-1";
+ credits_cost: number;
+ is_successful: boolean;
+ error?: string;
+ result?: any;
+ cost_tracking?: ReturnType<typeof CostTracking.prototype.toJSON>;
+};
+
+export async function logExtract(
+ extract: LoggedExtract,
+ force: boolean = false,
+) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logExtract",
+ extractId: extract.id,
+ requestId: extract.request_id,
+ teamId: extract.team_id,
+ });
+
+ await robustInsert(
+ "extracts",
+ {
+ id: extract.id,
+ request_id: extract.request_id,
+ urls: extract.urls,
+ team_id:
+ extract.team_id === "preview" || extract.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : extract.team_id,
+ options: extract.options,
+ model_kind: extract.model_kind,
+ credits_cost: extract.credits_cost,
+ is_successful: extract.is_successful,
+ error: extract.error ?? null,
+ cost_tracking: extract.cost_tracking ?? null,
+ },
+ force,
+ logger,
+ );
+
+ if (extract.result) {
+ await saveExtractToGCS(extract);
+ }
+}
+
+export type LoggedMap = {
+ id: string;
+ request_id: string;
+ url: string;
+ team_id: string;
+ options: any;
+ results: any[];
+ credits_cost: number;
+ zeroDataRetention: boolean;
+};
+
+export async function logMap(map: LoggedMap, force: boolean = false) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logMap",
+ mapId: map.id,
+ requestId: map.request_id,
+ teamId: map.team_id,
+ zeroDataRetention: map.zeroDataRetention,
+ });
+
+ await robustInsert(
+ "maps",
+ {
+ id: map.id,
+ request_id: map.request_id,
+ url: map.zeroDataRetention
+ ? "<redacted due to zero data retention>"
+ : map.url,
+ team_id:
+ map.team_id === "preview" || map.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : map.team_id,
+ options: map.zeroDataRetention ? null : map.options,
+ num_results: map.results.length,
+ credits_cost: map.credits_cost,
+ },
+ force,
+ logger,
+ );
+
+ if (map.results && !map.zeroDataRetention) {
+ await saveMapToGCS(map);
+ }
+}
+
+export type LoggedLlmsTxt = {
+ id: string;
+ request_id: string;
+ url: string;
+ team_id: string;
+ options: any;
+ num_urls: number;
+ cost_tracking?: ReturnType<typeof CostTracking.prototype.toJSON>;
+ credits_cost: number;
+ result: { llmstxt: string; llmsfulltxt: string };
+};
+
+export async function logLlmsTxt(
+ llmsTxt: LoggedLlmsTxt,
+ force: boolean = false,
+) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logLlmsTxt",
+ llmsTxtId: llmsTxt.id,
+ requestId: llmsTxt.request_id,
+ teamId: llmsTxt.team_id,
+ });
+
+ await robustInsert(
+ "llmstxts",
+ {
+ id: llmsTxt.id,
+ request_id: llmsTxt.request_id,
+ url: llmsTxt.url,
+ team_id:
+ llmsTxt.team_id === "preview" || llmsTxt.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : llmsTxt.team_id,
+ options: llmsTxt.options,
+ num_urls: llmsTxt.num_urls,
+ credits_cost: llmsTxt.credits_cost,
+ cost_tracking: llmsTxt.cost_tracking ?? null,
+ },
+ force,
+ logger,
+ );
+
+ if (llmsTxt.result) {
+ await saveLlmsTxtToGCS(llmsTxt);
+ }
+}
+
+export type LoggedDeepResearch = {
+ id: string;
+ request_id: string;
+ query: string;
+ team_id: string;
+ options: any;
+ time_taken: number;
+ credits_cost: number;
+ result: { finalAnalysis: string; sources: any; json: any };
+ cost_tracking?: ReturnType<typeof CostTracking.prototype.toJSON>;
+};
+
+export async function logDeepResearch(
+ deepResearch: LoggedDeepResearch,
+ force: boolean = false,
+) {
+ const logger = _logger.child({
+ module: "log_job",
+ method: "logDeepResearch",
+ deepResearchId: deepResearch.id,
+ requestId: deepResearch.request_id,
+ teamId: deepResearch.team_id,
+ });
+
+ await robustInsert(
+ "deep_researches",
+ {
+ id: deepResearch.id,
+ request_id: deepResearch.request_id,
+ query: deepResearch.query,
+ team_id:
+ deepResearch.team_id === "preview" ||
+ deepResearch.team_id?.startsWith("preview_")
+ ? previewTeamId
+ : deepResearch.team_id,
+ options: deepResearch.options,
+ time_taken: deepResearch.time_taken,
+ credits_cost: deepResearch.credits_cost,
+ cost_tracking: deepResearch.cost_tracking ?? null,
+ },
+ force,
+ logger,
+ );
- // if (process.env.POSTHOG_API_KEY && !job.crawl_id) {
- // await withSpan("firecrawl-log-job-posthog-capture", async span => {
- // setSpanAttributes(span, {
- // "log_job.operation": "posthog_capture",
- // "job.id": job.job_id,
- // "job.team_id": job.team_id,
- // "job.mode": job.mode,
- // });
-
- // const jobProperties = transformJobForLogging(job, {
- // includeTimestamp: false,
- // serializeObjects: false,
- // cleanNullValues: false,
- // });
-
- // let phLog = {
- // distinctId: "from-api", //* To identify this on the group level, setting distinctid to a static string per posthog docs: https://posthog.com/docs/product-analytics/group-analytics#advanced-server-side-only-capturing-group-events-without-a-user
- // ...(job.team_id !== "preview" &&
- // !job.team_id?.startsWith("preview_") && {
- // groups: { team: job.team_id },
- // }), //* Identifying event on this team
- // event: "job-logged",
- // properties: {
- // ...jobProperties,
- // // Remove docs from PostHog as it's not needed for analytics
- // docs: undefined,
- // },
- // };
-
- // if (job.mode !== "single_urls") {
- // posthog.capture(phLog);
- // setSpanAttributes(span, { "posthog.capture_sent": true });
- // } else {
- // setSpanAttributes(span, {
- // "posthog.capture_sent": false,
- // "posthog.skip_reason": "single_urls_mode",
- // });
- // }
- // });
- // }
- } catch (error) {
- logger.error(`Error logging job`, {
- error,
- });
+ if (deepResearch.result) {
+ await saveDeepResearchToGCS(deepResearch);
}
}
diff --git a/apps/api/src/services/posthog.ts b/apps/api/src/services/posthog.ts
deleted file mode 100644
index 02c9f7907..000000000
--- a/apps/api/src/services/posthog.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { PostHog } from "posthog-node";
-import "dotenv/config";
-import { logger } from "../../src/lib/logger";
-
-function PostHogClient(apiKey: string) {
- const posthogClient = new PostHog(apiKey, {
- host: process.env.POSTHOG_HOST,
- flushAt: 1,
- flushInterval: 0,
- });
- return posthogClient;
-}
-
-class MockPostHog {
- capture() {}
-}
-
-// Using the actual PostHog class if POSTHOG_API_KEY exists, otherwise using the mock class
-// Additionally, print a warning to the terminal if POSTHOG_API_KEY is not provided
-export const posthog = process.env.POSTHOG_API_KEY
- ? PostHogClient(process.env.POSTHOG_API_KEY)
- : (() => {
- logger.warn(
- "POSTHOG_API_KEY is not provided - your events will not be logged. Using MockPostHog as a fallback. See posthog.ts for more.",
- );
- return new MockPostHog();
- })();
diff --git a/apps/api/src/services/worker/crawl-logic.ts b/apps/api/src/services/worker/crawl-logic.ts
index eda2398f7..06dd1960a 100644
--- a/apps/api/src/services/worker/crawl-logic.ts
+++ b/apps/api/src/services/worker/crawl-logic.ts
@@ -7,7 +7,7 @@ import {
import { getCrawl } from "../../lib/crawl-redis";
import { supabase_service } from "../supabase";
import { getJobs } from "../../controllers/v1/crawl-status";
-import { logJob } from "../logging/log_job";
+import { logCrawl, logBatchScrape } from "../logging/log_job";
import { createWebhookSender, WebhookEvent } from "../webhook/index";
import type { NuQJob } from "./nuq";
@@ -57,26 +57,41 @@ export async function finishCrawlSuper(job: NuQJob<any>) {
)
.filter(x => x !== null);
- await logJob(
- {
- job_id: crawlId,
- success: jobStatus === "completed",
- message: sc.cancelled ? "Cancelled" : undefined,
- num_docs: fullDocs.length,
- docs: [],
- time_taken: (Date.now() - sc.createdAt) / 1000,
- team_id: job.data.team_id,
- mode: sc.crawlerOptions !== null ? "crawl" : "batch_scrape",
- url: sc.originUrl!,
- scrapeOptions: sc.scrapeOptions,
- crawlerOptions: sc.crawlerOptions,
- origin: sc.originUrl!,
- integration: job.data.integration,
- zeroDataRetention: job.data.zeroDataRetention,
- },
- false,
- sc.internalOptions?.bypassBilling ?? false,
- );
+ if (sc.crawlerOptions !== null) {
+ await logCrawl(
+ {
+ id: crawlId,
+ request_id: job.data.requestId ?? crawlId,
+ url: sc.originUrl!,
+ team_id: job.data.team_id,
+ options: sc.crawlerOptions,
+ num_docs: fullDocs.length,
+ credits_cost: fullDocs.reduce(
+ (acc, doc) => acc + (doc?.metadata?.creditsUsed ?? 0),
+ 0,
+ ),
+ zeroDataRetention: sc.zeroDataRetention || job.data.zeroDataRetention,
+ cancelled: sc.cancelled ?? false,
+ },
+ false,
+ );
+ } else {
+ await logBatchScrape(
+ {
+ id: crawlId,
+ request_id: job.data.requestId ?? crawlId,
+ team_id: job.data.team_id,
+ num_docs: fullDocs.length,
+ credits_cost: fullDocs.reduce(
+ (acc, doc) => acc + (doc?.metadata?.creditsUsed ?? 0),
+ 0,
+ ),
+ zeroDataRetention: sc.zeroDataRetention || job.data.zeroDataRetention,
+ cancelled: sc.cancelled ?? false,
+ },
+ false,
+ );
+ }
// v0 web hooks, call when done with all the data
if (!job.data.v1) {
@@ -110,13 +125,12 @@ export async function finishCrawlSuper(job: NuQJob<any>) {
}
} else {
const num_docs = await getDoneJobsOrderedLength(crawlId);
- const jobStatus = sc.cancelled ? "failed" : "completed";
let credits_billed = null;
if (process.env.USE_DB_AUTHENTICATION === "true") {
const creditsRpc = await supabase_service.rpc(
- "credits_billed_by_crawl_id_1",
+ "credits_billed_by_crawl_id_2",
{
i_crawl_id: crawlId,
},
@@ -131,29 +145,35 @@ export async function finishCrawlSuper(job: NuQJob<any>) {
}
}
- await logJob(
- {
- job_id: crawlId,
- success: jobStatus === "completed",
- message: sc.cancelled ? "Cancelled" : undefined,
- num_docs,
- docs: [],
- time_taken: (Date.now() - sc.createdAt) / 1000,
- team_id: sc.team_id,
- scrapeOptions: sc.scrapeOptions,
- mode: sc.crawlerOptions !== null ? "crawl" : "batch_scrape",
- url:
- sc?.originUrl ??
- (sc.crawlerOptions === null ? "Batch Scrape" : "Unknown"),
- crawlerOptions: sc.crawlerOptions,
- origin: job.data.origin,
- integration: job.data.integration,
- credits_billed,
- zeroDataRetention: job.data.zeroDataRetention,
- },
- true,
- sc.internalOptions?.bypassBilling ?? false,
- );
+ if (sc.crawlerOptions !== null) {
+ await logCrawl(
+ {
+ id: crawlId,
+ request_id: job.data.requestId ?? crawlId,
+ url: sc.originUrl!,
+ team_id: job.data.team_id,
+ options: sc.crawlerOptions,
+ num_docs: num_docs,
+ credits_cost: credits_billed ?? 0,
+ zeroDataRetention: sc.zeroDataRetention || job.data.zeroDataRetention,
+ cancelled: sc.cancelled ?? false,
+ },
+ false,
+ );
+ } else {
+ await logBatchScrape(
+ {
+ id: crawlId,
+ request_id: job.data.requestId ?? crawlId,
+ team_id: job.data.team_id,
+ num_docs: num_docs,
+ credits_cost: credits_billed ?? 0,
+ zeroDataRetention: sc.zeroDataRetention || job.data.zeroDataRetention,
+ cancelled: sc.cancelled ?? false,
+ },
+ false,
+ );
+ }
// v1 web hooks, call when done with no data, but with event completed
if (job.data.v1 && job.data.webhook) {
diff --git a/apps/api/src/services/worker/scrape-worker.ts b/apps/api/src/services/worker/scrape-worker.ts
index fb1b9f226..abeb11ffa 100644
--- a/apps/api/src/services/worker/scrape-worker.ts
+++ b/apps/api/src/services/worker/scrape-worker.ts
@@ -44,7 +44,6 @@ import { CostTracking } from "../../lib/cost-tracking";
import { normalizeUrlOnlyHostname } from "../../lib/canonical-url";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";
-import { logJob } from "../logging/log_job";
import { generateURLSplits, queryIndexAtSplitLevel } from "../index";
import { WebCrawler } from "../../scraper/WebScraper/crawler";
import { calculateCreditsToBeBilled } from "../../lib/scrape-billing";
@@ -73,6 +72,7 @@ import {
setSpanAttributes,
} from "../../lib/otel-tracer";
import { ScrapeUrlResponse } from "../../scraper/scrapeURL";
+import { logScrape } from "../logging/log_job";
configDotenv();
@@ -398,6 +398,7 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {
origin: job.data.origin,
integration: job.data.integration,
crawl_id: job.data.crawl_id,
+ requestId: job.data.requestId,
webhook: job.data.webhook,
v1: job.data.v1,
zeroDataRetention: job.data.zeroDataRetention,
@@ -456,31 +457,23 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {
doc.metadata.creditsUsed = credits_billed ?? undefined;
logger.debug("Logging job to DB...");
- await logJob(
+ await logScrape(
{
- job_id: job.id as string,
- success: true,
- num_docs: 1,
- docs: [doc],
+ id: job.id,
+ request_id: job.data.requestId ?? job.data.crawl_id ?? job.id,
+ url: job.data.url,
+ is_successful: true,
+ doc,
time_taken: timeTakenInSeconds,
team_id: job.data.team_id,
- mode: job.data.mode,
- url: job.data.url,
- crawlerOptions: sc.crawlerOptions,
- scrapeOptions: job.data.scrapeOptions,
- origin: job.data.origin,
- integration: job.data.integration,
- crawl_id: job.data.crawl_id,
- cost_tracking: costTracking,
+ options: job.data.scrapeOptions,
+ cost_tracking: costTracking.toJSON(),
pdf_num_pages: doc.metadata.numPages,
- credits_billed,
- change_tracking_tag:
- hasFormatOfType(job.data.scrapeOptions.formats, "changeTracking")
- ?.tag ?? null,
+ credits_cost: credits_billed ?? 0,
zeroDataRetention: job.data.zeroDataRetention,
+ skipNuq: job.data.skipNuq ?? false,
},
true,
- job.data.internalOptions?.bypassBilling ?? false,
);
if (job.data.v1) {
@@ -532,31 +525,23 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {
doc.metadata.creditsUsed = credits_billed ?? undefined;
- await logJob(
+ await logScrape(
{
- job_id: job.id,
- success: true,
- message: "Scrape completed",
- num_docs: 1,
- docs: [doc],
+ id: job.id,
+ request_id: job.data.requestId ?? job.data.crawl_id ?? job.id,
+ url: job.data.url,
+ is_successful: true,
+ doc,
time_taken: timeTakenInSeconds,
team_id: job.data.team_id,
- mode: "scrape",
- url: job.data.url,
- scrapeOptions: job.data.scrapeOptions,
- origin: job.data.origin,
- integration: job.data.integration,
- num_tokens: 0, // TODO: fix
- cost_tracking: costTracking,
+ options: job.data.scrapeOptions,
+ cost_tracking: costTracking.toJSON(),
pdf_num_pages: doc.metadata.numPages,
- credits_billed,
- change_tracking_tag:
- hasFormatOfType(job.data.scrapeOptions.formats, "changeTracking")
- ?.tag ?? null,
+ credits_cost: credits_billed ?? 0,
zeroDataRetention: job.data.zeroDataRetention,
+ skipNuq: job.data.skipNuq ?? false,
},
false,
- job.data.internalOptions?.bypassBilling ?? false,
);
}
@@ -690,32 +675,26 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {
);
logger.debug("Logging job to DB...");
- await logJob(
+ await logScrape(
{
- job_id: job.id as string,
- success: false,
- message:
+ id: job.id,
+ request_id: job.data.requestId ?? job.data.crawl_id ?? job.id,
+ url: job.data.url,
+ is_successful: false,
+ error:
typeof error === "string"
? error
: (error.message ??
"Something went wrong... Contact [email protected]"),
- num_docs: 0,
- docs: [],
time_taken: timeTakenInSeconds,
team_id: job.data.team_id,
- mode: job.data.mode,
- url: job.data.url,
- crawlerOptions: job.data.crawlerOptions,
- scrapeOptions: job.data.scrapeOptions,
- origin: job.data.origin,
- integration: job.data.integration,
- crawl_id: job.data.crawl_id,
- cost_tracking: costTracking,
- credits_billed,
+ options: job.data.scrapeOptions,
+ cost_tracking: costTracking.toJSON(),
+ credits_cost: credits_billed ?? 0,
zeroDataRetention: job.data.zeroDataRetention,
+ skipNuq: job.data.skipNuq ?? false,
},
true,
- job.data.internalOptions?.bypassBilling ?? false,
);
return data;
} finally {
@@ -794,6 +773,7 @@ async function addKickoffSitemapJob(
origin: sourceJob.data.origin,
integration: sourceJob.data.integration,
crawl_id: sourceJob.data.crawl_id,
+ requestId: sourceJob.data.requestId,
webhook: sourceJob.data.webhook,
v1: sourceJob.data.v1,
apiKeyId: sourceJob.data.apiKeyId,
@@ -845,6 +825,7 @@ async function processKickoffJob(job: NuQJob<ScrapeJobKickoff>) {
origin: job.data.origin,
integration: job.data.integration,
crawl_id: job.data.crawl_id,
+ requestId: job.data.requestId,
webhook: job.data.webhook,
v1: job.data.v1,
isCrawlSourceScrape: true,
@@ -931,6 +912,7 @@ async function processKickoffJob(job: NuQJob<ScrapeJobKickoff>) {
origin: job.data.origin,
integration: job.data.integration,
crawl_id: job.data.crawl_id,
+ requestId: job.data.requestId,
sitemapped: true,
webhook: job.data.webhook,
v1: job.data.v1,
@@ -1037,6 +1019,7 @@ async function processKickoffSitemapJob(job: NuQJob<ScrapeJobKickoffSitemap>) {
origin: job.data.origin,
integration: job.data.integration,
crawl_id: job.data.crawl_id,
+ requestId: job.data.requestId,
sitemapped: true,
webhook: job.data.webhook,
v1: job.data.v1,
diff --git a/apps/api/src/types.ts b/apps/api/src/types.ts
index 11dd06418..1acfb5a6a 100644
--- a/apps/api/src/types.ts
+++ b/apps/api/src/types.ts
@@ -18,6 +18,7 @@ type ScrapeJobCommon = {
zeroDataRetention: boolean;
traceContext?: SerializedTraceContext;
skipNuq?: boolean;
+ requestId?: string;
};
export type ScrapeJobData = ScrapeJobCommon &
@@ -102,34 +103,6 @@ export interface RunWebScraperParams {
costTracking: CostTracking;
}
-export interface FirecrawlJob {
- job_id?: string;
- success: boolean;
- message?: string;
- num_docs: number;
- docs: any[];
- time_taken: number;
- team_id: string;
- mode: string;
- url: string;
- crawlerOptions?: any;
- scrapeOptions?: any;
- origin: string;
- integration?: string | null;
- num_tokens?: number;
- retry?: boolean;
- crawl_id?: string;
- tokens_billed?: number;
- sources?: Record<string, string[]>;
- cost_tracking?: CostTracking;
- pdf_num_pages?: number;
- credits_billed?: number | null;
- change_tracking_tag?: string | null;
- dr_clean_by?: string | null;
-
- zeroDataRetention: boolean;
-}
-
export interface FirecrawlScrapeResponse {
statusCode: number;
body: {
diff --git a/docker-compose.yaml b/docker-compose.yaml
index 184e1d60e..9c72edf55 100644
--- a/docker-compose.yaml
+++ b/docker-compose.yaml
@@ -39,8 +39,6 @@ x-common-env: &common-env
SLACK_WEBHOOK_URL: ${SLACK_WEBHOOK_URL}
BULL_AUTH_KEY: ${BULL_AUTH_KEY}
TEST_API_KEY: ${TEST_API_KEY}
- POSTHOG_API_KEY: ${POSTHOG_API_KEY}
- POSTHOG_HOST: ${POSTHOG_HOST}
SUPABASE_ANON_TOKEN: ${SUPABASE_ANON_TOKEN}
SUPABASE_URL: ${SUPABASE_URL}
SUPABASE_SERVICE_TOKEN: ${SUPABASE_SERVICE_TOKEN}
diff --git a/examples/kubernetes/cluster-install/secret.yaml b/examples/kubernetes/cluster-install/secret.yaml
index 78fb800cf..c749e7c6a 100644
--- a/examples/kubernetes/cluster-install/secret.yaml
+++ b/examples/kubernetes/cluster-install/secret.yaml
@@ -9,8 +9,6 @@ data:
LLAMAPARSE_API_KEY: ""
BULL_AUTH_KEY: ""
TEST_API_KEY: ""
- POSTHOG_API_KEY: ""
- POSTHOG_HOST: ""
STRIPE_PRICE_ID_STANDARD: ""
STRIPE_PRICE_ID_SCALE: ""
FIRE_ENGINE_BETA_URL: ""
diff --git a/examples/kubernetes/firecrawl-helm/templates/secret.yaml b/examples/kubernetes/firecrawl-helm/templates/secret.yaml
index 94add392f..3840b7c4e 100644
--- a/examples/kubernetes/firecrawl-helm/templates/secret.yaml
+++ b/examples/kubernetes/firecrawl-helm/templates/secret.yaml
@@ -9,8 +9,6 @@ data:
LLAMAPARSE_API_KEY: {{ .Values.secret.LLAMAPARSE_API_KEY | b64enc | quote }}
BULL_AUTH_KEY: {{ .Values.secret.BULL_AUTH_KEY | b64enc | quote }}
TEST_API_KEY: {{ .Values.secret.TEST_API_KEY | b64enc | quote }}
- POSTHOG_API_KEY: {{ .Values.secret.POSTHOG_API_KEY | b64enc | quote }}
- POSTHOG_HOST: {{ .Values.secret.POSTHOG_HOST | b64enc | quote }}
SCRAPING_BEE_API_KEY: {{ .Values.secret.SCRAPING_BEE_API_KEY | b64enc | quote }}
STRIPE_PRICE_ID_STANDARD: {{ .Values.secret.STRIPE_PRICE_ID_STANDARD | b64enc | quote }}
STRIPE_PRICE_ID_SCALE: {{ .Values.secret.STRIPE_PRICE_ID_SCALE | b64enc | quote }}
diff --git a/examples/kubernetes/firecrawl-helm/values.yaml b/examples/kubernetes/firecrawl-helm/values.yaml
index 4f4f0ca68..853462b3d 100644
--- a/examples/kubernetes/firecrawl-helm/values.yaml
+++ b/examples/kubernetes/firecrawl-helm/values.yaml
@@ -75,8 +75,6 @@ secret:
LLAMAPARSE_API_KEY: ""
BULL_AUTH_KEY: ""
TEST_API_KEY: ""
- POSTHOG_API_KEY: ""
- POSTHOG_HOST: ""
SCRAPING_BEE_API_KEY: ""
STRIPE_PRICE_ID_STANDARD: ""
STRIPE_PRICE_ID_SCALE: ""