function sessionize()

in packages/sqrl-redis-functions/src/RateLimitFunctions.ts [260:321]


    function sessionize(state: CompileState, ast: CustomCallAst): Ast {
      const args: RateLimitArguments = parse(ast.source, {
        startRule: "RateLimitArguments",
      });
      const { whereAst, whereFeatures, whereTruth } = state.combineGlobalWhere(
        args.where
      );

      const tokenAmountAst = state.setGlobal(
        ast,
        AstBuilder.branch(
          whereAst,
          AstBuilder.call("_getTokenAmount", [args.tokenAmount]),
          AstBuilder.constant(0)
        )
      );

      const { entityId, entityAst } = state.addHashedEntity(ast, "Sessionize", {
        whereFeatures,
        whereTruth,
        features: args.features,
        maxAmount: args.maxAmount,
        refillTimeMs: args.refillTimeMs,
        refillAmount: args.refillAmount,
      });

      const keyAst = state.setGlobal(
        ast,
        AstBuilder.call("_buildKey", [entityAst, ...args.features]),
        `key(${entityId.getIdString()})`
      );

      // Convert the amount to be taken into a new global, this allows the
      // entire array below to be pre-computed.
      const takeAst = state.setGlobal(
        ast,
        AstBuilder.branch(
          AstBuilder.feature("SqrlMutate"),
          tokenAmountAst,
          AstBuilder.constant(0)
        )
      );

      const sessionTimestampSlot = state.setGlobal(
        ast,
        AstBuilder.call("_fetchSession", [
          AstBuilder.props({
            key: keyAst,
            maxAmount: AstBuilder.constant(args.maxAmount),
            refillTimeMs: AstBuilder.constant(args.refillTimeMs),
            refillAmount: AstBuilder.constant(args.refillAmount),
            take: takeAst,
            at: AstBuilder.call("timeMs", [AstBuilder.feature("SqrlClock")]),
          }),
        ])
      );

      return AstBuilder.call("_sessionize", [
        keyAst, // Key for the session rate limit
        sessionTimestampSlot,
      ]);
    },