'''
'''
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

Test.Summary = '''
Test prefetch.so does not self-prefetch when a valid pattern's replacement collapses to an empty path.

The replacement here is just "$3", where group 3 ("(\\?.*)?") is optional.  For a query-less request
that group is absent, so the replacement expands to the empty string.  An empty expanded path would
otherwise be scheduled with zero length, which BgFetch skips -- leaving the pristine request path and
prefetching the URL itself.  The plugin must instead log and stop; the client request is still served.
'''

server = Test.MakeOriginServer("server")
for i in list(range(1, 1 + 2)):
    request_header = {
        "headers":
            f"GET /texts/demo-{i} HTTP/1.1\r\n"
            "Host: does.not.matter\r\n"  # But cannot be omitted.
            "\r\n",
        "timestamp": "1469733493.993",
        "body": ""
    }
    response_header = {
        "headers": "HTTP/1.1 200 OK\r\n"
                   "Connection: close\r\n"
                   "Cache-control: max-age=85000\r\n"
                   "\r\n",
        "timestamp": "1469733493.993",
        "body": f"This is the body for demo-{i}.\n"
    }
    server.addResponse("sessionlog.json", request_header, response_header)

dns = Test.MakeDNServer("dns")

ts = Test.MakeATSProcess("ts")
ts.Disk.records_config.update(
    {
        'proxy.config.diags.debug.enabled': 1,
        'proxy.config.diags.debug.tags': 'http|dns|prefetch',
        'proxy.config.dns.nameservers': f"127.0.0.1:{dns.Variables.Port}",
        'proxy.config.dns.resolv_conf': "NULL",
    })
# A valid pattern (3 defined groups, $3 in range) whose replacement is only the optional $3 group.
ts.Disk.remap_config.AddLine(
    f"map http://domain.in http://127.0.0.1:{server.Variables.Port}" + " @plugin=cachekey.so @pparam=--remove-all-params=true"
    " @plugin=prefetch.so" + " @pparam=--front=true" + " @pparam=--fetch-policy=simple" +
    r" @pparam=--fetch-path-pattern=/(.*-)(\d+)(\?.*)?$/$3/" + " @pparam=--fetch-count=3")
ts.ReturnCode = Any(0, -2)

# The empty replacement must be logged and skipped.  This ContainsExpression both asserts the message
# and replaces the default "diags.log must not contain ERROR:" check (it is logged via TSError).
ts.Disk.diags_log.Content = Testers.ContainsExpression(
    "produced an empty path", "an empty replacement must be logged and skipped, not self-prefetched")

tr = Test.AddTestRun()
tr.Processes.Default.StartBefore(server)
tr.Processes.Default.StartBefore(dns)
tr.Processes.Default.StartBefore(ts)
tr.Processes.Default.Command = 'echo start TS, HTTP server and DNS.'
tr.Processes.Default.ReturnCode = 0

# The client request is still served normally even though the prefetch is skipped.
tr = Test.AddTestRun()
tr.MakeCurlCommand(f'--verbose --proxy 127.0.0.1:{ts.Variables.port} http://domain.in/texts/demo-1')
tr.Processes.Default.ReturnCode = 0

Test.AddAwaitFileContainsTestRun('Await the empty-path skip to be logged.', ts.Disk.diags_log.Name, 'produced an empty path')

# The self-prefetch that the old code issued would re-fetch the original path.  With the fix the loop
# stops before scheduling, so "failed to process the pattern" (the old second-iteration symptom on the
# emptied working path) must never appear.
tr = Test.AddTestRun()
tr.Processes.Default.Command = (f"grep -c 'failed to process the pattern' {ts.Disk.traffic_out.Name} || true")
tr.Streams.stdout = Testers.ContainsExpression("0", "no per-request pattern-processing failure")
tr.Processes.Default.ReturnCode = 0
