Repository navigation
Conversation
| // Removes "Bearer " and trims | ||
| const token = authorizationHeader.split(' ')[1].trim(); | ||
| // Load user for later middleware/routes to use | ||
| req.user = await User.newUser({ token }); |
There was a problem hiding this comment.
User.newUser is misleading, it does not create a new user, instead it retrieves a user based on the JWT token.
There was a problem hiding this comment.
User.fromToken({ token }) or User.getByToken({ token }) would be a better fit.
There was a problem hiding this comment.
Yup agreed. I was using existing methods though.
| const appDefinition = backendJsFile.Definition; | ||
|
|
||
| const backend = createFriggBackend(appDefinition); | ||
| const loadRouterFromObject = (IntegrationClass, routerObject) => { |
There was a problem hiding this comment.
"Object" is too vague, I have no clue what can be in there or what that means
There was a problem hiding this comment.
I think we could call it loadIntegrationRoutes
There was a problem hiding this comment.
Also the routerObject is already inside of IntegrationClass isn't it?
There was a problem hiding this comment.
The overall method of loadIntegrationRoutes makes sense, or integration defined routes.
The load from object method was intended to load from a... route object? Dunno what to call it. The "method", "path", "event" object. I'm not even sure where I got that concept from except it's a common way to represent an http endpoint. Minus the event thing. That I want to be an easy way for a dev to reference when creating event handlers.
|
|
||
| for (const routeDef of IntegrationClass.Definition.routes) { | ||
| if (typeof routeDef === 'function') { | ||
| router.use(basePath, routeDef(IntegrationClass)); |
There was a problem hiding this comment.
I don't understand this.
You're looping through IntegrationClass.Definition.routes and from every routeDef you're passing the same integration as parameter?
There was a problem hiding this comment.
Do you have an example of a place where we declare routes as a function and need it's own integration class as parameter?
There was a problem hiding this comment.
Why not stick to one type of route definition? Either function or object
There was a problem hiding this comment.
I think the rationale was that in some cases, you need to have some logic that runs outside of express route generation. https://github.com/lefthookhq/frigg-2.0-prototyping/blob/460ad99b85b5a53bac5a859de8b8d3780b85937d/backend/src/testRouter.js#L8
In other cases, relying on the normal instantiation is fine and for those you can reach for either the straight express route or the static object.
I wanted to provide a "quick and easy", "moderate complexity", "high complexity" set of options.
That said I'm not sure what I did was the way to do it.
| router[method.toLowerCase()](path, async (req, res, next) => { | ||
| try { | ||
| const integration = new IntegrationClass({}); | ||
| await integration.loadModules(); |
There was a problem hiding this comment.
We already loadModules in the IntegrationBase constructor, we could registerEventHandlers in the constructor as well.
There was a problem hiding this comment.
I think I had an issue of not wanting to load event handlers yet because of some dynamic issues? Or something else. But, happy to not duplicate invoking!
| await integration.loadModules(); | ||
| await integration.registerEventHandlers(); | ||
| const result = await integration.send(event, {req, res, next}); | ||
| res.json(result); |
There was a problem hiding this comment.
Do we really have to return the result here?
Developers will by instict call the http response when it's available to them. I was not aware that this existed until now and probably other developers won't either.
There was a problem hiding this comment.
Well, the intent was to remove the need to think about express inside the handler function. Just, do what you need, then if you need to return something, return it.
There was a problem hiding this comment.
But if someones sees a "res" object, one would not simply return and ignore "res".
BTW, one of the reasons I don't like ruby on rails is because it does too much magic and I don't know why and how 🫠
| for (const [entityId, key] of Object.entries( | ||
| integrationRecord.entityReference | ||
| )) { | ||
| const moduleInstance = |
There was a problem hiding this comment.
Are the modules not already instantiated in IntegrationBase -> loadModules() when we do:
const instance = new integrationClass({
userId,
integrationId: params.integrationId,
});
There was a problem hiding this comment.
OK, looks like loadModules doesn't actualy loads modules but it simply instantiates the module api.
There was a problem hiding this comment.
There's a difference between "load module definitions" and "load module entities into the module instance"
| integrationRecord.config.type | ||
| ); | ||
|
|
||
| const instance = new integrationClass({ |
There was a problem hiding this comment.
rename to integrationInstance
| // for each entity, get the moduleinstance and load them according to their keys | ||
| // If it's the first entity, load the moduleinstance into primary as well | ||
| // If it's the second entity, load the moduleinstance into target as well | ||
| const moduleTypesAndKeys = |
There was a problem hiding this comment.
I think this comment also does not make sense anymore, right?
There was a problem hiding this comment.
The first line does make sense. The second and third lines are for backwards compatibility, where we enforced a "primary" and "target" concept via naming conventions.
There was a problem hiding this comment.
I don't think we need to maintain that though. Let things error and people correct the errors.
| moduleClass && | ||
| typeof moduleClass.definition.getName === 'function' | ||
| ) { | ||
| const moduleType = moduleClass.definition.getName(); |
There was a problem hiding this comment.
moduleType also comes from the name?
There was a problem hiding this comment.
Yes, though we can debate that
| const integrationClassIndex = this.integrationTypes.indexOf(type); | ||
| return this.integrationClasses[integrationClassIndex]; | ||
| } | ||
| getModuleTypesAndKeys(integrationClass) { |
There was a problem hiding this comment.
I dont get what this does
There was a problem hiding this comment.
I don't think this implementation is fully what I intended. But anywho, the goal is that we grab an integration definition, and from it we can determine which api modules are part of it, which allows us to get the required module entity instances in order to create a complete integration record (TODO allow for a module to be optional and not required on creation of an integration record, potentially make them required on a per event basis, ie we throw an error/force a user to assign a connection or create a new connection if they go to use a feature that is only available if they have a specific module instance added).
The direct use case is during the management inside the frontend experience. The ui should see "user wants to create a HubSpot integration. The HubSpot integration requires two modules. The user has one module connection (entity) available to use, but needs the other one. I'll run the auth flow for the other one and then ask them to confirm the use of that new connection."
The reason I say this implementation may not be what I intended is that we should allow multiple modules of the same type to be assigned different module names so you have something like "slackUser" and "slackApp" both pointing to the slack api module.
seanspeaks
left a comment
There was a problem hiding this comment.
Did my comments to your comments and a few added comments in there
| { | ||
| "$schema": "node_modules/lerna/schemas/lerna-schema.json", | ||
| "version": "1.2.2", | ||
| "version": "2.0.0-next.0", |
There was a problem hiding this comment.
I have no idea if this should be committed 😅
| const appDefinition = backendJsFile.Definition; | ||
|
|
||
| const backend = createFriggBackend(appDefinition); | ||
| const loadRouterFromObject = (IntegrationClass, routerObject) => { |
There was a problem hiding this comment.
The overall method of loadIntegrationRoutes makes sense, or integration defined routes.
The load from object method was intended to load from a... route object? Dunno what to call it. The "method", "path", "event" object. I'm not even sure where I got that concept from except it's a common way to represent an http endpoint. Minus the event thing. That I want to be an easy way for a dev to reference when creating event handlers.
| router[method.toLowerCase()](path, async (req, res, next) => { | ||
| try { | ||
| const integration = new IntegrationClass({}); | ||
| await integration.loadModules(); |
There was a problem hiding this comment.
I think I had an issue of not wanting to load event handlers yet because of some dynamic issues? Or something else. But, happy to not duplicate invoking!
|
|
||
| getIntegrationById: async function(id) { | ||
| return IntegrationModel.findById(id); | ||
| getIntegrationById: async function (id) { |
There was a problem hiding this comment.
I really need to lock this concept into my brain. Git repo takes the entire definition of "repository" in my head.
| const integration = | ||
| await integrationFactory.getInstanceFromIntegrationId({ | ||
| integrationId: integrationRecord.id, | ||
| userId: getUserId(req), |
There was a problem hiding this comment.
I think we discussed this on our call. Likely just was throwing things that stuck, for context on why this is here.
| @@ -349,9 +375,7 @@ function setEntityRoutes(router, factory, getUserId) { | |||
| throw Boom.forbidden('Credential does not belong to user'); | |||
There was a problem hiding this comment.
I think there were moments where this failed? Dunno what those moments were/are though.
| const {ModuleConstants} = require("./ModuleConstants"); | ||
| const { ModuleConstants } = require('./ModuleConstants'); | ||
|
|
||
| class Auther extends Delegate { |
There was a problem hiding this comment.
All for it. At one point @MichaelRyanWebber and I were debating both naming and intent of the class (hi Michael! Not to rope you in but, you likely can either find the note somewhere or comment on the future improvements you/we had in mind).
| this.EntityModel = definition.Entity || this.getEntityModel(); | ||
| } | ||
|
|
||
| static async getInstance(params) { |
There was a problem hiding this comment.
Async construction.
It's a debate in nodejs world. Might be a resolved debate in node 20? But basically "if you need to await/promise something in order to instantiate a class, do you make it an async constructor, or do you create a static async instantiation method?" Aka the get
That's the root of this decision at any rate.
There was a problem hiding this comment.
CodeQL found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.
️✅ There are no secrets present in this pull request anymore.If these secrets were true positive and are still valid, we highly recommend you to revoke them. 🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request. |
|
There was a problem hiding this comment.
SonarCloud found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.
|
✅ Deploy Preview for friggframework-org canceled.
|
How to use this.logger in integrations and API modules: which ids come for free per entry point, messages and eventNames, levels, the error rule, late ids with child(), what not to log, levels per app, queries, tests with a memory sink, migrating console calls, and a full example. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
API modules declare their limits and how to read a throttled response. The Requester waits in process for a short wait and throws RateLimitError with retryAt for a long one; the queue worker defers the message instead of spending a delivery. The last-attempt signal stays the fallback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
API modules (headers and body reason, docs-only limits, a non-Requester client, a module that declares nothing), the Requester throttled branch, a Retry-After parser, RateLimitError, the halt rule, Worker.run deferral, an integration handler and the RATE_LIMITED message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… start serverless-offline copies only AWS_* shell variables into handlers, so FRIGG_LOG_LEVEL=warn frigg start had no effect and IS_OFFLINE forced DEBUG. In local mode the composer now puts the shell (or .env) value into the function env, where it wins over logging.level, and emits logging.level INFO too. Deploys never read the shell value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… cost - One table of record-contract keys (logs/contract-keys.js) for record.js and the denylist protection; one isError, deepFreeze and isPlainObject. - The error field is serialized once; bindings are copied once; the scope is serialized once per invocation (WeakMap on the ALS store); the record is stringified once unless a field is dropped. - Keys are normalized once per walk, with one suffix regex. - Call sites pass only the extra request details under invocation, so record.js merges with a plain spread. - Dead code removed: the scrubTokens segment mode, a duplicated sink retry block, a try/catch that could not catch. A scoped info record with a child binding: ~37 µs → ~18 µs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A slow usage DB write could use up the remaining Lambda time and skip the telemetry and sink flush. The deadline is now fixed at flush start and the usage rollup runs next to the bounded flush. droppedKeys lists only real conflicts, not a binding that repeats the scope value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EncryptionLogger maps TRACE to DEBUG and FATAL to ERROR. Every denylist registration warns once per skipped record-contract key (logs/denied-keys.js), also on the Prisma registry path. User update errors carry the user id. The websocket router requires the real repository factory path, so the Lambda loads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cess is gone The worker record for that failure now carries error.code, like the process use cases already do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Queue messages may carry integrationId and processId at the top level or under data. Webhook and Definition.routes dispatches with an :integrationId route param put that id in the logger scope only (never the telemetry context, which drives usage writes). A hydrated id in the store wins over a logger-only id. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
feat(core): add queryMappings to IntegrationMappingRepository
feat(core): tell queue handlers their last delivery attempt
# Conflicts: # packages/core/CLAUDE.md # packages/core/core/Worker.js
ADR-049 section 5 and the frigg#657 and frigg#658 reviews: the component that defers writes the message, not a Requester or module delegate. The default handler calls the recordRateLimitMessage hook only when the wait is over 900 s, retryAt is unknown (the message has the probe time), or a cap ended the deferrals. It writes nothing for a short wait, for a skipped deferral, or when the RATE_LIMITED handler drops or retries. A failing hook logs rate_limit_message_failed and keeps the outcome. The QueueWorker writes the warning through RecordRateLimitMessage on the integration that ran the job. The use case builds the client-safe shape kept from frigg#658 (code, module, reason, ISO UTC retryAt, RETRY_WHEN_READY and LINK actions) with the text and links of the userHints of the module that the event names, keyed by reason. It writes through the atomic appendRateLimitMessage, so concurrent workers write one warning, and the type keeps its newest 50 items. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The default handler of phase 2 writes the message, so phase 4 ships in frigg#657 and frigg#658 closes. Also say that an unknown value from the RATE_LIMITED handler counts as 'defer'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A virtual mock of @aws-sdk/client-scheduler is missed when an earlier test file in the same jest worker (Worker.deferral.test.js) already resolved the real package, so five lazy-loading tests failed in CI. The package is a hard dependency, so a plain mock covers the same cases in any order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rror The raw MongoDB and DocumentDB update command returns write errors in its result instead of throwing, so a failed append looked like a stored message. The Worker hook logs the throw as rate_limit_message_failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A dropped message never runs again, so a WAITING Process.context.rateLimit that it set stayed until another wait replaced it. Clear it as after a success, with the same deferralId rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SonarCloud S3403 read the string checks on the base hook's result as always false and failed the reliability gate. A Map lookup states the three outcomes in one place; any other value, also a prototype key, still runs the default handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
index.js re-exports RateLimitError at runtime, but types/core/index.d.ts did not declare it, so a strict TypeScript import gave TS2305. Re-export the declaration from @friggframework/errors and type-check a strict consumer in a test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
inProcessBudgetMs read requestTimeoutMs: 0 as a 0 ms reserve, so a Requester with no request timeout could sleep until the invocation deadline and leave no time for the next request. 0, null or a missing value means the request has no time limit, so keep the largest reserve: half the time left. With no deadline there is nothing to keep. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parseResetValue read a millisecond delta such as X-RateLimit-Reset: 60000 as 60000 s. The size of a delta cannot show its unit: 60000 s (16.7 h) is also a real daily reset, and HubSpot, Pipedrive and Salesforce (api-module-library#102) send no millisecond delta. So a module that gets one declares static rateLimit.resetDeltaUnit = 'ms'. Epoch seconds and epoch milliseconds keep their size rules, and an unknown unit throws a TypeError, like an unknown parser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The express boundary and the user-facing createHandler catch answered
a RateLimitError with a generic 500. Both now map any error with
isRateLimited to 429, Retry-After in seconds from retryAt (none when
retryAt is unknown) and { error: 'Too Many Requests', retryAt }, and
log one WARN record with the error. The mapping lives in the HTTP
adapter (core/rate-limited-response.js), not in the error. A
server-to-server handler still rethrows, so the queue worker can defer.
429, not 503: the default scope counts the limit against the caller's
own entity, and a 503 would fire 5xx alarms for an expected state.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A classify that names a 404 (or another response that is not a limit) as a limit with a time makes the Requester retry it up to 10 times and then throw RateLimitError. Say so in the Rate Limits reference, and pin the behaviour with a test so the warning stays true. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The RATE_LIMITED event carries scopeKey, but the token refresh transport error copied every rate-limit field except it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/guides/LOGGING.md sets the eventName at the call site, so the full frigg.worker.record_deferral_capped and record_visibility_extended names now appear as literals and can be found with a search. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd host The scheduler role took the region from the second label of the queue host and hard-coded the aws partition, so a legacy queue.amazonaws.com URL got a wrong region, a China or GovCloud stack a wrong partition, and a queue.url that resolves after the build (a Serverless variable or a CloudFormation function) threw. The shared helper leaves the partition to the stack, reads the region of every SQS host form, and lets CloudFormation split a value that is not a URL yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The base role grants SendMessage, GetQueueUrl, GetQueueAttributes and ChangeMessageVisibility only on the queues the stack names, so for ownership.queue 'external' the delay and visibility tiers of a rate-limit deferral were denied and fell back to SQS redelivery. ADR-049 gives the base role these actions in every stack, so the integration builder now adds them on the external queue's ARN. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add resetDeltaUnit for a reset delta in milliseconds, the 429 answer of an HTTP route, scopeKey on the rate-limited token error, and the queue actions that the functions get on an external queue. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…son-04ff ci: fix MongoDB replica-set flake + add Cloud Agent environment.json
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…it-defer Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…it-followups Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ester feat(core): honour Retry-After and let API modules declare rate limits
feat(core): defer rate-limited queue messages through a RATE_LIMITED event
Keeps the requestTimeoutMs: 0 note from this branch and the 0 s queue-worker budget from #657. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ness docs(adr): ADR-049 rate-limit awareness
…owups fix(core): address the #656 rate-limit review follow-ups
|




Version
Published prerelease version:
v2.0.0-next.129Changelog
🎉 This release contains work from a new contributor! 🎉
Thank you, Cursor Agent (@cursoragent), for all your work!
Release Notes
feat(core): defer rate-limited queue messages through a RATE_LIMITED event (#657)
@friggframework/coreand@friggframework/devtoolstogether, and redeploy. Devtools grants the IAM actions and switches on the scheduler; core does the deferral.Retry-Afteror a classified limit could wait in process (up to 60 s with feat(core): honour Retry-After and let API modules declare rate limits #656). Now the message is deferred at once and the handler runs again from the start atretryAt. So:FRIGG_QUEUE_MAX_DEFERRALS(30). A job with many calls that keeps hitting a short burst limit can reach the cap and fail; keep each message's work small, or raise the cap;RateLimitErrorthat the Requester used to retry in process. Rethrow it.A 429 with no hint keeps the fixed
backOffladder, as before.RATE_LIMITEDevent handler, and a module can adduserHintstext and links to itsstatic rateLimit. New env var:FRIGG_QUEUE_RATE_LIMIT_PROBE_MS.🤖 Generated with Claude Code
feat(core): honour Retry-After and let API modules declare rate limits (#656)
@friggframework/coreand redeploys. A module that declares nothing keeps its behaviour, except that a 429 withRetry-Afternow waits as long as the header says when that fits the caller's budget, and throwsRateLimitErrorwhen it does not.@friggframework/corebefore an API module usesstatic rateLimitorRateLimitError.🤖 Generated with Claude Code
🚀 Enhancement
@friggframework/core@friggframework/core,@friggframework/devtools@friggframework/admin-scripts,@friggframework/core,@friggframework/devtools,@friggframework/eslint-config,@friggframework/prettier-config,@friggframework/schemas,@friggframework/serverless-plugin,@friggframework/test,@friggframework/ui🐛 Bug Fix
@friggframework/core,@friggframework/devtools@friggframework/admin-scripts,@friggframework/core,@friggframework/devtools,@friggframework/eslint-config,@friggframework/prettier-config,@friggframework/schemas,@friggframework/serverless-plugin,@friggframework/test,@friggframework/uiAuthors: 4