File: models.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (2642 lines) | stat: -rw-r--r-- 103,158 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
from __future__ import annotations

import base64
import calendar
import copy
import hashlib
import io
import json
import logging
import os
import re
import tarfile
import threading
import time
import warnings
import weakref
import zipfile
from collections import defaultdict
from collections.abc import Iterable
from datetime import datetime
from gzip import GzipFile
from sys import platform
from typing import Any, Optional, TypedDict, Union

import requests.exceptions

from moto import settings
from moto.awslambda.policy import Policy
from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import BaseModel, CloudFormationModel
from moto.core.exceptions import RESTError
from moto.core.utils import iso_8601_datetime_with_nanoseconds, unix_time_millis, utcnow
from moto.dynamodb import dynamodb_backends
from moto.dynamodbstreams import dynamodbstreams_backends
from moto.ecr.exceptions import ImageNotFoundException
from moto.ecr.models import ecr_backends
from moto.iam.exceptions import NotFoundException as IAMNotFoundException
from moto.iam.models import iam_backends
from moto.kinesis.models import KinesisBackend, kinesis_backends
from moto.logs.models import logs_backends
from moto.moto_api._internal import mock_random as random
from moto.s3.exceptions import MissingBucket, MissingKey
from moto.s3.models import FakeKey, s3_backends
from moto.sqs.models import sqs_backends
from moto.utilities.docker_utilities import DockerModel
from moto.utilities.utils import (
    ARN_PARTITION_REGEX,
    get_partition,
    load_resource_as_bytes,
)

from .exceptions import (
    ConflictException,
    CrossAccountNotAllowed,
    GenericResourcNotFound,
    InvalidParameterValueException,
    InvalidRoleFormat,
    LambdaClientError,
    UnknownAliasException,
    UnknownEventConfig,
    UnknownFunctionException,
    UnknownLayerException,
    UnknownLayerVersionException,
    ValidationException,
)
from .utils import (
    make_event_source_mapping_arn,
    make_function_arn,
    make_function_ver_arn,
    make_layer_arn,
    make_layer_ver_arn,
    split_layer_arn,
)

logger = logging.getLogger(__name__)


class LayerDataType(TypedDict):
    Arn: str
    CodeSize: int


def zip2tar(zip_bytes: bytes) -> io.BytesIO:
    tarstream = io.BytesIO()
    timeshift = int((datetime.now() - utcnow()).total_seconds())
    tarf = tarfile.TarFile(fileobj=tarstream, mode="w")
    with zipfile.ZipFile(io.BytesIO(zip_bytes), "r") as zipf:
        for zipinfo in zipf.infolist():
            if zipinfo.is_dir():
                continue

            tarinfo = tarfile.TarInfo(name=zipinfo.filename)
            tarinfo.size = zipinfo.file_size
            tarinfo.mtime = calendar.timegm(zipinfo.date_time) - timeshift
            infile = zipf.open(zipinfo.filename)
            tarf.addfile(tarinfo, infile)

    tarstream.seek(0)
    return tarstream


def file2tar(file_content: bytes, file_name: str) -> io.BytesIO:
    tarstream = io.BytesIO()
    tarf = tarfile.TarFile(fileobj=tarstream, mode="w")
    tarinfo = tarfile.TarInfo(name=file_name)
    tarinfo.size = len(file_content)
    tarf.addfile(tarinfo, io.BytesIO(file_content))

    tarstream.seek(0)
    return tarstream


class _VolumeRefCount:
    __slots__ = "refcount", "volume"

    def __init__(self, refcount: int, volume: Any):
        self.refcount = refcount
        self.volume = volume


class _DockerDataVolumeContext:
    # {sha256: _VolumeRefCount}
    _data_vol_map: dict[str, _VolumeRefCount] = defaultdict(
        lambda: _VolumeRefCount(0, None)
    )
    _lock = threading.Lock()

    def __init__(self, lambda_func: LambdaFunction):
        self._lambda_func = lambda_func
        self._vol_ref: Optional[_VolumeRefCount] = None

    @property
    def name(self) -> str:
        return self._vol_ref.volume.name  # type: ignore[union-attr]

    def __enter__(self) -> _DockerDataVolumeContext:
        # See if volume is already known
        with self.__class__._lock:
            self._vol_ref = self.__class__._data_vol_map[self._lambda_func.code_digest]
            self._vol_ref.refcount += 1
            if self._vol_ref.refcount > 1:
                return self

            # See if the volume already exists
            for vol in self._lambda_func.docker_client.volumes.list():
                if vol.name == self._lambda_func.code_digest:
                    self._vol_ref.volume = vol
                    return self

            # It doesn't exist so we need to create it
            self._vol_ref.volume = self._lambda_func.docker_client.volumes.create(
                self._lambda_func.code_digest
            )
            volumes = {self.name: {"bind": settings.LAMBDA_DATA_DIR, "mode": "rw"}}

            self._lambda_func.ensure_image_exists("busybox")
            container = self._lambda_func.docker_client.containers.run(
                "busybox", "sleep 100", volumes=volumes, detach=True
            )
            try:
                with zip2tar(self._lambda_func.code_bytes) as stream:
                    container.put_archive(settings.LAMBDA_DATA_DIR, stream)
                if settings.is_test_proxy_mode():
                    ca_cert = load_resource_as_bytes(__name__, "../moto_proxy/ca.crt")
                    with file2tar(ca_cert, "ca.crt") as cert_stream:
                        container.put_archive(settings.LAMBDA_DATA_DIR, cert_stream)
            finally:
                container.remove(force=True)

        return self

    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        with self.__class__._lock:
            self._vol_ref.refcount -= 1  # type: ignore[union-attr]
            if self._vol_ref.refcount == 0:  # type: ignore[union-attr]
                import docker.errors

                try:
                    self._vol_ref.volume.remove()  # type: ignore[union-attr]
                except docker.errors.APIError as e:
                    if e.status_code != 409:
                        raise

                    raise  # multiple processes trying to use same volume?


class _DockerDataVolumeLayerContext:
    _data_vol_map: dict[str, _VolumeRefCount] = defaultdict(
        lambda: _VolumeRefCount(0, None)
    )
    _lock = threading.Lock()

    def __init__(self, lambda_func: LambdaFunction):
        self._lambda_func = lambda_func
        self._layers: list[LayerDataType] = self._lambda_func.layers
        self._vol_ref: Optional[_VolumeRefCount] = None

    @property
    def name(self) -> str:
        return self._vol_ref.volume.name  # type: ignore[union-attr]

    @property
    def hash(self) -> str:
        return "-".join(
            [
                layer["Arn"].split("layer:")[-1].replace(":", "_")
                for layer in self._layers
            ]
        )

    def __enter__(self) -> _DockerDataVolumeLayerContext:
        # See if volume is already known
        with self.__class__._lock:
            self._vol_ref = self.__class__._data_vol_map[self.hash]
            self._vol_ref.refcount += 1
            if self._vol_ref.refcount > 1:
                return self

            # See if the volume already exists
            for vol in self._lambda_func.docker_client.volumes.list():
                if vol.name == self.hash:
                    self._vol_ref.volume = vol
                    return self

            # It doesn't exist so we need to create it
            self._vol_ref.volume = self._lambda_func.docker_client.volumes.create(
                self.hash
            )
            # If we don't have any layers to apply, just return at this point
            # When invoking the function, we will bind this empty volume
            if len(self._layers) == 0:
                return self
            volumes = {self.name: {"bind": "/opt", "mode": "rw"}}

            self._lambda_func.ensure_image_exists("busybox")
            container = self._lambda_func.docker_client.containers.run(
                "busybox", "sleep 100", volumes=volumes, detach=True
            )
            backend: LambdaBackend = lambda_backends[self._lambda_func.account_id][
                self._lambda_func.region
            ]
            try:
                for layer in self._layers:
                    try:
                        layer_zip = backend.layers_versions_by_arn(  # type: ignore[union-attr]
                            layer["Arn"]
                        ).code_bytes
                        layer_tar = zip2tar(layer_zip)
                        container.put_archive("/opt", layer_tar)
                    except zipfile.BadZipfile as e:
                        warnings.warn(
                            f"Error extracting layer to Lambda: {e}", stacklevel=2
                        )
            finally:
                container.remove(force=True)

        return self

    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        with self.__class__._lock:
            self._vol_ref.refcount -= 1  # type: ignore[union-attr]
            if self._vol_ref.refcount == 0:  # type: ignore[union-attr]
                import docker.errors

                try:
                    self._vol_ref.volume.remove()  # type: ignore[union-attr]
                except docker.errors.APIError as e:
                    if e.status_code != 409:
                        raise

                    raise  # multiple processes trying to use same volume?


def _zipfile_content(zipfile_content: Union[str, bytes]) -> tuple[bytes, int, str, str]:
    try:
        to_unzip_code = base64.b64decode(bytes(zipfile_content, "utf-8"))  # type: ignore[arg-type]
    except Exception:
        to_unzip_code = base64.b64decode(zipfile_content)

    sha_code = hashlib.sha256(to_unzip_code)
    base64ed_sha = base64.b64encode(sha_code.digest()).decode("utf-8")
    sha_hex_digest = sha_code.hexdigest()
    return to_unzip_code, len(to_unzip_code), base64ed_sha, sha_hex_digest


def _s3_content(key: Any) -> tuple[bytes, int, str, str]:
    sha_code = hashlib.sha256(key.value)
    base64ed_sha = base64.b64encode(sha_code.digest()).decode("utf-8")
    sha_hex_digest = sha_code.hexdigest()
    return key.value, key.size, base64ed_sha, sha_hex_digest


def _validate_s3_bucket_and_key(
    account_id: str, partition: str, data: dict[str, Any]
) -> Optional[FakeKey]:
    key = None
    try:
        # FIXME: does not validate bucket region
        key = s3_backends[account_id][partition].get_object(
            data["S3Bucket"], data["S3Key"]
        )
    except MissingBucket:
        if do_validate_s3():
            raise InvalidParameterValueException(
                "Error occurred while GetObject. S3 Error Code: NoSuchBucket. S3 Error Message: The specified bucket does not exist"
            )
    except MissingKey:
        if do_validate_s3():
            raise ValueError(
                "InvalidParameterValueException",
                "Error occurred while GetObject. S3 Error Code: NoSuchKey. S3 Error Message: The specified key does not exist.",
            )
    return key


class EventInvokeConfig:
    def __init__(self, arn: str, last_modified: str, config: dict[str, Any]) -> None:
        self.config = config
        self.validate_max()
        self.validate()
        self.arn = arn
        self.last_modified = last_modified

    def validate_max(self) -> None:
        if "MaximumRetryAttempts" in self.config:
            mra = self.config["MaximumRetryAttempts"]
            if mra > 2:
                raise ValidationException(
                    mra,
                    "maximumRetryAttempts",
                    "Member must have value less than or equal to 2",
                )

            # < 0 validation done by botocore
        if "MaximumEventAgeInSeconds" in self.config:
            mra = self.config["MaximumEventAgeInSeconds"]
            if mra > 21600:
                raise ValidationException(
                    mra,
                    "maximumEventAgeInSeconds",
                    "Member must have value less than or equal to 21600",
                )

            # < 60 validation done by botocore

    def validate(self) -> None:
        # https://docs.aws.amazon.com/lambda/latest/dg/API_OnSuccess.html
        regex = r"^$|arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)"
        pattern = re.compile(regex)

        if self.config["DestinationConfig"]:
            destination_config = self.config["DestinationConfig"]
            if (
                "OnSuccess" in destination_config
                and "Destination" in destination_config["OnSuccess"]
            ):
                contents = destination_config["OnSuccess"]["Destination"]
                if not pattern.match(contents):
                    raise ValidationException(
                        contents,
                        "destinationConfig.onSuccess.destination",
                        f"Member must satisfy regular expression pattern: {regex}",
                    )
            if (
                "OnFailure" in destination_config
                and "Destination" in destination_config["OnFailure"]
            ):
                contents = destination_config["OnFailure"]["Destination"]
                if not pattern.match(contents):
                    raise ValidationException(
                        contents,
                        "destinationConfig.onFailure.destination",
                        f"Member must satisfy regular expression pattern: {regex}",
                    )

    def response(self) -> dict[str, Any]:
        response = {"FunctionArn": self.arn, "LastModified": self.last_modified}
        response.update(self.config)
        return response


class ImageConfig:
    def __init__(self, config: dict[str, Any]) -> None:
        self.cmd = config.get("Command", [])
        self.entry_point = config.get("EntryPoint", [])
        self.working_directory = config.get("WorkingDirectory", None)

    def response(self) -> dict[str, Any]:
        content = {
            "Command": self.cmd,
            "EntryPoint": self.entry_point,
        }
        if self.working_directory is not None:
            content["WorkingDirectory"] = self.working_directory
        return dict(content)


class Permission(CloudFormationModel):
    def __init__(self, region: str):
        self.region = region

    @staticmethod
    def cloudformation_name_type() -> str:
        return "Permission"

    @staticmethod
    def cloudformation_type() -> str:
        return "AWS::Lambda::Permission"

    @classmethod
    def create_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
        **kwargs: Any,
    ) -> Permission:
        properties = cloudformation_json["Properties"]
        backend = lambda_backends[account_id][region_name]
        fn = backend.get_function(properties["FunctionName"])
        fn.policy.add_statement(raw=json.dumps(properties))
        return Permission(region=region_name)


class LayerVersion(CloudFormationModel):
    def __init__(self, spec: dict[str, Any], account_id: str, region: str):
        # required
        self.account_id = account_id
        self.region = region
        self.name = spec["LayerName"]
        self.content = spec["Content"]

        # optional
        self.description = spec.get("Description", "")
        self.compatible_architectures = spec.get("CompatibleArchitectures", [])
        self.compatible_runtimes = spec.get("CompatibleRuntimes", [])
        self.license_info = spec.get("LicenseInfo", "")
        self.policy = Policy(self)  # type: ignore[no-untyped-call]

        # For `list_layer_versions`, AWS sends back a hardcoded string over the wire, with timezone info automatically set to UTC (+0000)
        # This despite the fact that the layer exists in the US (us-east-1), and my local timezone was set to UTC+2
        # So it seems like the date is automatically set to UTC on creation, that's why we can just return this hardcoded
        # Also add microseconds to be compatible with AWS (milliseconds '%f' adds six, we only want three chars)
        self.created_date = utcnow().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "+0000"
        self.version: int = 1
        self._attached = False
        self._layer: Optional[Layer] = None

        if "ZipFile" in self.content:
            (
                self.code_bytes,
                self.code_size,
                self.code_sha_256,
                self.code_digest,
            ) = _zipfile_content(self.content["ZipFile"])
        else:
            partition = get_partition(region)
            key = _validate_s3_bucket_and_key(
                account_id, partition=partition, data=self.content
            )
            if key:
                (
                    self.code_bytes,
                    self.code_size,
                    self.code_sha_256,
                    self.code_digest,
                ) = _s3_content(key)
            else:
                self.code_bytes = b""
                self.code_size = 0
                self.code_sha_256 = ""
                self.code_digest = ""

    @property
    def arn(self) -> str:
        if self.version:
            return make_layer_ver_arn(
                self.region, self.account_id, self.name, self.version
            )
        raise ValueError("Layer version is not set")

    def attach(self, layer: Layer, version: int) -> None:
        self._attached = True
        self._layer = layer
        self.version = version

    def get_layer_version(self) -> dict[str, Any]:
        version = {
            "Content": {
                "Location": "s3://",
                "CodeSha256": self.code_sha_256,
                "CodeSize": self.code_size,
            },
            "Version": self.version,
            "LayerArn": self._layer.layer_arn,  # type: ignore[union-attr]
            "LayerVersionArn": self.arn,
            "CreatedDate": self.created_date,
            "LicenseInfo": self.license_info,
        }
        if self.description:
            version["Description"] = self.description
        if self.compatible_architectures:
            version["CompatibleArchitectures"] = self.compatible_architectures
        if self.compatible_runtimes:
            version["CompatibleRuntimes"] = self.compatible_runtimes
        return version

    @staticmethod
    def cloudformation_name_type() -> str:
        return "LayerVersion"

    @staticmethod
    def cloudformation_type() -> str:
        return "AWS::Lambda::LayerVersion"

    @classmethod
    def create_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
        **kwargs: Any,
    ) -> LayerVersion:
        properties = cloudformation_json["Properties"]
        optional_properties = ("Description", "CompatibleRuntimes", "LicenseInfo")

        # required
        spec = {
            "Content": properties["Content"],
            "LayerName": resource_name,
        }
        for prop in optional_properties:
            if prop in properties:
                spec[prop] = properties[prop]

        backend = lambda_backends[account_id][region_name]
        layer_version = backend.publish_layer_version(spec)
        return layer_version


class LambdaAlias(BaseModel):
    def __init__(
        self,
        account_id: str,
        region: str,
        name: str,
        function_name: str,
        function_version: str,
        description: str,
        routing_config: str,
    ):
        self.arn = f"arn:{get_partition(region)}:lambda:{region}:{account_id}:function:{function_name}:{name}"
        self.name = name
        self.function_version = function_version
        self.description = description
        self.routing_config = routing_config
        self.revision_id = str(random.uuid4())

    def update(
        self,
        description: Optional[str],
        function_version: Optional[str],
        routing_config: Optional[str],
    ) -> None:
        if description is not None:
            self.description = description
        if function_version is not None:
            self.function_version = function_version
        if routing_config is not None:
            self.routing_config = routing_config

    def to_json(self) -> dict[str, Any]:
        return {
            "AliasArn": self.arn,
            "Description": self.description,
            "FunctionVersion": self.function_version,
            "Name": self.name,
            "RevisionId": self.revision_id,
            "RoutingConfig": self.routing_config or None,
        }


class Layer:
    def __init__(self, layer_version: LayerVersion):
        self.region = layer_version.region
        self.name = layer_version.name

        self.layer_arn = make_layer_arn(
            self.region, layer_version.account_id, self.name
        )
        self._latest_version = 0
        self.layer_versions: dict[str, LayerVersion] = {}

    def attach_version(self, layer_version: LayerVersion) -> None:
        self._latest_version += 1
        layer_version.attach(self, self._latest_version)
        self.layer_versions[str(self._latest_version)] = layer_version

    def delete_version(self, layer_version: str) -> None:
        self.layer_versions.pop(str(layer_version), None)

    def to_dict(self) -> dict[str, Any]:
        if not self.layer_versions:
            return {}

        last_key = sorted(self.layer_versions.keys(), key=lambda version: int(version))[
            -1
        ]
        return {
            "LayerName": self.name,
            "LayerArn": self.layer_arn,
            "LatestMatchingVersion": self.layer_versions[last_key].get_layer_version(),
        }


class LambdaFunction(CloudFormationModel, DockerModel):
    def __init__(
        self,
        account_id: str,
        spec: dict[str, Any],
        region: str,
        version: Union[str, int] = 1,
    ):
        DockerModel.__init__(self)
        # required
        self.account_id = account_id
        self.region = region
        self.partition = get_partition(region)
        self.code = spec["Code"]
        self.function_name = spec["FunctionName"]
        self.handler = spec.get("Handler")
        self.role = spec["Role"]
        self.run_time = spec.get("Runtime")
        self.logs_backend = logs_backends[account_id][self.region]
        self.environment_vars = spec.get("Environment", {}).get("Variables", {})
        self.policy = Policy(self)  # type: ignore[no-untyped-call]
        self.url_config: Optional[FunctionUrlConfig] = None
        self.state = "Active"
        self.reserved_concurrency = spec.get("ReservedConcurrentExecutions", None)

        # optional
        self.ephemeral_storage: str
        self.code_digest: str
        self.code_bytes: bytes
        self.event_invoke_config: list[EventInvokeConfig] = []

        self.description = spec.get("Description", "")
        self.memory_size = spec.get("MemorySize", 128)
        self.package_type = spec.get("PackageType", "Zip")
        self.publish = spec.get("Publish", False)  # this is ignored currently
        self.timeout = spec.get("Timeout", 3)
        self.layers: list[LayerDataType] = self._get_layers_data(spec.get("Layers", []))
        self.signing_profile_version_arn = spec.get("SigningProfileVersionArn")
        self.signing_job_arn = spec.get("SigningJobArn")
        self.code_signing_config_arn = spec.get("CodeSigningConfigArn")
        self.tracing_config = spec.get("TracingConfig") or {"Mode": "PassThrough"}
        self.architectures: list[str] = spec.get("Architectures", ["x86_64"])
        self.image_config: ImageConfig = ImageConfig(spec.get("ImageConfig", {}))
        _es = spec.get("EphemeralStorage")
        if _es:
            self.ephemeral_storage = _es["Size"]
        else:
            self.ephemeral_storage = 512

        self.logs_group_name = f"/aws/lambda/{self.function_name}"

        # VpcConfig has no default, if not supplied
        self._vpc_config = spec.get("VpcConfig")

        # auto-generated
        self.version = version
        self.last_modified = iso_8601_datetime_with_nanoseconds()

        self._set_function_code(self.code)
        self.code_or_config_updated = False

        self.function_arn: str = make_function_arn(
            self.region, self.account_id, self.function_name
        )

        self.tags = spec.get("Tags") or {}

    def __getstate__(self) -> dict[str, Any]:
        return {
            k: v
            for (k, v) in self.__dict__.items()
            if k != "_DockerModel__docker_client"
        }

    def set_version(self, version: int) -> None:
        self.function_arn = make_function_ver_arn(
            self.region, self.account_id, self.function_name, version
        )
        self.version = version
        self.last_modified = iso_8601_datetime_with_nanoseconds()

    @property
    def architectures(self) -> list[str]:
        return self._architectures

    @architectures.setter
    def architectures(self, architectures: list[str]) -> None:
        if (
            len(architectures) > 1
            or not architectures
            or architectures[0] not in ("x86_64", "arm64")
        ):
            raise ValidationException(
                str(architectures),
                "architectures",
                "Member must satisfy constraint: "
                "[Member must satisfy enum value set: [x86_64, arm64], Member must not be null]",
            )
        self._architectures = architectures

    @property
    def ephemeral_storage(self) -> int:
        return self._ephemeral_storage

    @ephemeral_storage.setter
    def ephemeral_storage(self, ephemeral_storage: int) -> None:
        if ephemeral_storage > 10240:
            raise ValidationException(
                str(ephemeral_storage),
                "ephemeralStorage.size",
                "Member must have value less than or equal to 10240",
            )

        # ephemeral_storage < 512 is handled by botocore 1.30.0
        self._ephemeral_storage = ephemeral_storage

    @property
    def vpc_config(self) -> Optional[dict[str, Any]]:  # type: ignore[misc]
        if not self._vpc_config:
            return None
        config = self._vpc_config.copy()
        if config["SecurityGroupIds"]:
            config.update({"VpcId": "vpc-123abc"})
        return config

    @property
    def physical_resource_id(self) -> str:
        return self.function_name

    def __repr__(self) -> str:
        return json.dumps(self.get_configuration())

    def _get_layers_data(self, layers_versions_arns: list[str]) -> list[LayerDataType]:
        backend = lambda_backends[self.account_id][self.region]
        layer_versions = [
            backend.layers_versions_by_arn(layer_version)
            for layer_version in layers_versions_arns
        ]
        if not all(layer_versions):
            raise UnknownLayerVersionException(layers_versions_arns)
        # The `if lv` part is not necessary - we know there are no None's, because of the `all()`-check earlier
        # But MyPy does not seem to understand this
        return [
            {"Arn": lv.arn, "CodeSize": lv.code_size} for lv in layer_versions if lv
        ]

    def get_function_code_signing_config(self) -> dict[str, Any]:
        return {
            "CodeSigningConfigArn": self.code_signing_config_arn,
            "FunctionName": self.function_name,
        }

    def get_configuration(self, on_create: bool = False) -> dict[str, Any]:
        config = {
            "CodeSha256": self.code_sha_256,
            "CodeSize": self.code_size,
            "Description": self.description,
            "FunctionArn": self.function_arn,
            "FunctionName": self.function_name,
            "Handler": self.handler,
            "LastModified": self.last_modified,
            "MemorySize": self.memory_size,
            "Role": self.role,
            "Runtime": self.run_time,
            "State": self.state,
            "PackageType": self.package_type,
            "Timeout": self.timeout,
            "Version": str(self.version),
            "VpcConfig": self.vpc_config,
            "Layers": self.layers,
            "SigningProfileVersionArn": self.signing_profile_version_arn,
            "SigningJobArn": self.signing_job_arn,
            "TracingConfig": self.tracing_config,
            "Architectures": self.architectures,
            "EphemeralStorage": {
                "Size": self.ephemeral_storage,
            },
            "SnapStart": {"ApplyOn": "None", "OptimizationStatus": "Off"},
        }
        if self.package_type == "Image":
            config["ImageConfigResponse"] = {
                "ImageConfig": self.image_config.response(),
            }
        if not on_create:
            # Only return this variable after the first creation
            config["LastUpdateStatus"] = "Successful"
        if self.environment_vars:
            config["Environment"] = {"Variables": self.environment_vars}

        return config

    def get_code(self) -> dict[str, Any]:
        resp = {"Configuration": self.get_configuration()}
        if "S3Key" in self.code:
            resp["Code"] = {
                "Location": f"https://awslambda-{self.region}-tasks.s3.{self.region}.amazonaws.com/{self.code['S3Key']}",
                "RepositoryType": "S3",
            }
        elif "ImageUri" in self.code:
            resp["Code"] = {
                "RepositoryType": "ECR",
                "ImageUri": self.code.get("ImageUri"),
                "ResolvedImageUri": self.code.get("ImageUri").split(":")[0]
                + "@sha256:"
                + self.code_sha_256,
            }
        if self.tags:
            resp["Tags"] = self.tags
        if self.reserved_concurrency:
            resp.update(
                {
                    "Concurrency": {
                        "ReservedConcurrentExecutions": self.reserved_concurrency
                    }
                }
            )
        return resp

    def update_configuration(self, config_updates: dict[str, Any]) -> dict[str, Any]:
        for key, value in config_updates.items():
            if key == "Description":
                self.description = value
            elif key == "Handler":
                self.handler = value
            elif key == "MemorySize":
                self.memory_size = value
            elif key == "Role":
                self.role = value
            elif key == "Runtime":
                self.run_time = value
            elif key == "Timeout":
                self.timeout = value
            elif key == "VpcConfig":
                self._vpc_config = value
            elif key == "Environment":
                self.environment_vars = value["Variables"]
            elif key == "Layers":
                self.layers = self._get_layers_data(value)

        self.code_or_config_updated = True

        return self.get_configuration()

    def _set_function_code(self, updated_spec: dict[str, Any]) -> None:
        from_update = updated_spec is not self.code

        # "DryRun" is only used for UpdateFunctionCode
        if from_update and "DryRun" in updated_spec and updated_spec["DryRun"]:
            return

        if "ZipFile" in updated_spec:
            if from_update:
                self.code["ZipFile"] = updated_spec["ZipFile"]

            (
                self.code_bytes,
                self.code_size,
                self.code_sha_256,
                self.code_digest,
            ) = _zipfile_content(updated_spec["ZipFile"])

            # TODO: we should be putting this in a lambda bucket
            self.code["UUID"] = str(random.uuid4())
            self.code["S3Key"] = f"{self.function_name}-{self.code['UUID']}"
        elif "S3Bucket" in updated_spec and "S3Key" in updated_spec:
            key = None
            try:
                if from_update:
                    # FIXME: does not validate bucket region
                    key = s3_backends[self.account_id][self.partition].get_object(
                        updated_spec["S3Bucket"], updated_spec["S3Key"]
                    )
                else:
                    key = _validate_s3_bucket_and_key(
                        self.account_id, partition=self.partition, data=self.code
                    )
            except MissingBucket:
                if do_validate_s3():
                    raise ValueError(
                        "InvalidParameterValueException",
                        "Error occurred while GetObject. S3 Error Code: NoSuchBucket. S3 Error Message: The specified bucket does not exist",
                    )
            except MissingKey:
                if do_validate_s3():
                    raise ValueError(
                        "InvalidParameterValueException",
                        "Error occurred while GetObject. S3 Error Code: NoSuchKey. S3 Error Message: The specified key does not exist.",
                    )
            if key:
                (
                    self.code_bytes,
                    self.code_size,
                    self.code_sha_256,
                    self.code_digest,
                ) = _s3_content(key)
            else:
                self.code_bytes = b""
                self.code_size = 0
                self.code_sha_256 = ""
            if from_update:
                self.code["S3Bucket"] = updated_spec["S3Bucket"]
                self.code["S3Key"] = updated_spec["S3Key"]
        elif "ImageUri" in updated_spec:
            if settings.lambda_stub_ecr():
                self.code_sha_256 = hashlib.sha256(
                    updated_spec["ImageUri"].encode("utf-8")
                ).hexdigest()
                self.code_size = 0
            else:
                if "@" in updated_spec["ImageUri"]:
                    # deploying via digest
                    uri, digest = updated_spec["ImageUri"].split("@")
                    image_id = {"imageDigest": digest}
                else:
                    # deploying via tag
                    uri, tag = updated_spec["ImageUri"].split(":")
                    image_id = {"imageTag": tag}

                repo_name = uri.split("/")[-1]
                ecr_backend = ecr_backends[self.account_id][self.region]
                registry_id = ecr_backend.describe_registry()["registryId"]
                images = ecr_backend.batch_get_image(
                    repository_name=repo_name, image_ids=[image_id]
                )["images"]

                if len(images) == 0:
                    exc = ImageNotFoundException(image_id, repo_name, registry_id)  # type: ignore
                    raise LambdaClientError(exc.code, exc.message)
                else:
                    manifest = json.loads(images[0].image_manifest)
                    self.code_sha_256 = (
                        images[0].image_id["imageDigest"].replace("sha256:", "")
                    )
                    self.code_size = manifest["config"]["size"]
            if from_update:
                self.code["ImageUri"] = updated_spec["ImageUri"]

    def update_function_code(self, updated_spec: dict[str, Any]) -> dict[str, Any]:
        self._set_function_code(updated_spec)
        self.code_or_config_updated = True
        return self.get_configuration()

    @staticmethod
    def convert(s: Any) -> str:  # type: ignore[misc]
        try:
            return str(s, encoding="utf-8")
        except Exception:
            return s

    def _invoke_lambda(self, event: Optional[str] = None) -> tuple[str, bool, str]:
        import docker
        import docker.errors

        # Create the LogGroup if necessary, to write the result to
        self.logs_backend.ensure_log_group(self.logs_group_name)
        # TODO: context not yet implemented
        if event is None:
            event = {}  # type: ignore[assignment]
        output = None

        try:
            # TODO: I believe we can keep the container running and feed events as needed
            #       also need to hook it up to the other services so it can make kws/s3 etc calls
            #  Should get invoke_id /RequestId from invocation
            env_vars = {
                "_HANDLER": self.handler,
                "AWS_EXECUTION_ENV": f"AWS_Lambda_{self.run_time}",
                "AWS_LAMBDA_FUNCTION_TIMEOUT": self.timeout,
                "AWS_LAMBDA_FUNCTION_NAME": self.function_name,
                "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": self.memory_size,
                "AWS_LAMBDA_FUNCTION_VERSION": self.version,
                "AWS_REGION": self.region,
                "AWS_ACCESS_KEY_ID": "role-account-id",
                "AWS_SECRET_ACCESS_KEY": "role-secret-key",
                "AWS_SESSION_TOKEN": "session-token",
            }

            env_vars.update(self.environment_vars)
            env_vars["MOTO_HOST"] = settings.moto_server_host()
            moto_port = settings.moto_server_port()
            env_vars["MOTO_PORT"] = moto_port
            env_vars["MOTO_HTTP_ENDPOINT"] = f"{env_vars['MOTO_HOST']}:{moto_port}"

            if settings.is_test_proxy_mode():
                env_vars["HTTPS_PROXY"] = env_vars["MOTO_HTTP_ENDPOINT"]
                env_vars["AWS_CA_BUNDLE"] = "/var/task/ca.crt"

            container = exit_code = None
            log_config = docker.types.LogConfig(type=docker.types.LogConfig.types.JSON)

            with (
                _DockerDataVolumeContext(self) as data_vol,
                _DockerDataVolumeLayerContext(self) as layer_context,
            ):
                try:
                    run_kwargs: dict[str, Any] = {}
                    network_name = settings.moto_network_name()
                    network_mode = settings.moto_network_mode()
                    if network_name:
                        run_kwargs["network"] = network_name
                    elif network_mode:
                        run_kwargs["network_mode"] = network_mode
                    elif settings.TEST_SERVER_MODE:
                        # AWSLambda can make HTTP requests to a Docker container called 'motoserver'
                        # Only works if our Docker-container is named 'motoserver'
                        # TODO: should remove this and rely on 'network_mode' instead, as this is too tightly coupled with our own test setup
                        run_kwargs["links"] = {"motoserver": "motoserver"}

                    # add host.docker.internal host on linux to emulate Mac + Windows behavior
                    #   for communication with other mock AWS services running on localhost
                    if platform == "linux" or platform == "linux2":
                        run_kwargs["extra_hosts"] = {
                            "host.docker.internal": "host-gateway"
                        }

                    # Change entry point if requested
                    if self.image_config.entry_point:
                        run_kwargs["entrypoint"] = self.image_config.entry_point

                    # The requested image can be found in one of a few repos:
                    # - User-provided repo
                    # - mlupin/docker-lambda (the repo with up-to-date AWSLambda images
                    # - lambci/lambda (the repo with older/outdated AWSLambda images
                    #
                    # We'll cycle through all of them - when we find the repo that contains our image, we use it
                    image_repos = {  # dict maintains insertion order
                        settings.moto_lambda_image(): None,
                        "mlupin/docker-lambda": None,
                        "lambci/lambda": None,
                    }
                    for image_repo in image_repos:
                        image_ref = (
                            image_repo
                            if ":" in image_repo
                            else f"{image_repo}:{self.run_time}"
                        )
                        try:
                            self.ensure_image_exists(image_ref)
                            break
                        except docker.errors.NotFound:
                            pass
                    volumes = {
                        data_vol.name: {"bind": "/var/task", "mode": "rw"},
                        layer_context.name: {"bind": "/opt", "mode": "rw"},
                    }
                    container = self.docker_client.containers.run(
                        image_ref,
                        [self.handler, json.dumps(event)],
                        remove=False,
                        mem_limit=f"{self.memory_size}m",
                        volumes=volumes,
                        environment=env_vars,
                        detach=True,
                        log_config=log_config,
                        **run_kwargs,
                    )
                finally:
                    if container:
                        try:
                            exit_code = container.wait(timeout=300)["StatusCode"]
                        except requests.exceptions.ReadTimeout:
                            exit_code = -1
                            container.stop()
                            container.kill()

                        output = container.logs(stdout=False, stderr=True)
                        output += container.logs(stdout=True, stderr=False)
                        container.remove()

            output = output.decode("utf-8")  # type: ignore[union-attr]

            self.save_logs(output)

            # We only care about the response from the lambda
            # Which is the last line of the output, according to https://github.com/lambci/docker-lambda/issues/25
            resp = output.splitlines()[-1]
            logs = os.linesep.join(list(self.convert(output).splitlines()[:-1]))
            invocation_error = exit_code != 0
            return resp, invocation_error, logs
        except docker.errors.DockerException as e:
            # Docker itself is probably not running - there will be no Lambda-logs to handle
            msg = f"error running docker: {e}"
            logger.error(msg)
            self.save_logs(msg)
            return msg, True, ""

    def save_logs(self, output: str) -> None:
        # Send output to "logs" backend
        invoke_id = random.uuid4().hex
        date = utcnow()
        log_stream_name = (
            f"{date.year}/{date.month:02d}/{date.day:02d}/[{self.version}]{invoke_id}"
        )
        self.logs_backend.create_log_stream(self.logs_group_name, log_stream_name)
        log_events = [
            {"timestamp": unix_time_millis(), "message": line}
            for line in output.splitlines()
        ]
        self.logs_backend.put_log_events(
            self.logs_group_name, log_stream_name, log_events
        )

    def invoke(
        self, body: str, request_headers: Any, response_headers: Any
    ) -> Union[str, bytes]:
        if body:
            body = json.loads(body)
        else:
            body = "{}"

        # Get the invocation type:
        res, errored, logs = self._invoke_lambda(event=body)
        if errored:
            response_headers["x-amz-function-error"] = "Handled"

        inv_type = request_headers.get("x-amz-invocation-type", "RequestResponse")
        if inv_type == "RequestResponse":
            encoded = base64.b64encode(logs.encode("utf-8"))
            response_headers["x-amz-log-result"] = encoded.decode("utf-8")
            return res.encode("utf-8")
        else:
            return res

    @staticmethod
    def cloudformation_name_type() -> str:
        return "FunctionName"

    @staticmethod
    def cloudformation_type() -> str:
        # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html
        return "AWS::Lambda::Function"

    @classmethod
    def create_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
        **kwargs: Any,
    ) -> LambdaFunction:
        properties = cloudformation_json["Properties"]
        optional_properties = (
            "Description",
            "MemorySize",
            "Publish",
            "Timeout",
            "VpcConfig",
            "Environment",
            "ReservedConcurrentExecutions",
        )

        # required
        spec = {
            "Code": properties["Code"],
            "FunctionName": resource_name,
            "Handler": properties.get("Handler"),
            "Role": properties["Role"],
            "Runtime": properties.get("Runtime"),
        }

        # NOTE: Not doing `properties.get(k, DEFAULT)` to avoid duplicating the
        # default logic
        for prop in optional_properties:
            if prop in properties:
                spec[prop] = properties[prop]

        # when ZipFile is present in CloudFormation, per the official docs,
        # the code it's a plaintext code snippet up to 4096 bytes.
        # this snippet converts this plaintext code to a proper base64-encoded ZIP file.
        if "ZipFile" in properties["Code"]:
            spec["Code"]["ZipFile"] = base64.b64encode(
                cls._create_zipfile_from_plaintext_code(spec["Code"]["ZipFile"])
            )

        backend = lambda_backends[account_id][region_name]
        fn = backend.create_function(spec)
        return fn

    @classmethod
    def has_cfn_attr(cls, attr: str) -> bool:
        return attr in ["Arn"]

    def get_cfn_attribute(self, attribute_name: str) -> str:
        from moto.cloudformation.exceptions import UnformattedGetAttTemplateException

        if attribute_name == "Arn":
            return make_function_arn(self.region, self.account_id, self.function_name)
        raise UnformattedGetAttTemplateException()

    @classmethod
    def update_from_cloudformation_json(  # type: ignore[misc]
        cls,
        original_resource: LambdaFunction,
        new_resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
    ) -> LambdaFunction:
        updated_props = cloudformation_json["Properties"]
        original_resource.update_configuration(updated_props)
        original_resource.update_function_code(updated_props["Code"])
        return original_resource

    @staticmethod
    def _create_zipfile_from_plaintext_code(code: str) -> bytes:
        zip_output = io.BytesIO()
        zip_file = zipfile.ZipFile(zip_output, "w", zipfile.ZIP_DEFLATED)
        zip_file.writestr("index.py", code)
        # This should really be part of the 'lambci' docker image
        from moto.packages.cfnresponse import cfnresponse

        with open(cfnresponse.__file__) as cfn:
            zip_file.writestr("cfnresponse.py", cfn.read())
        zip_file.close()
        zip_output.seek(0)
        return zip_output.read()

    def delete(self, account_id: str, region: str) -> None:
        lambda_backends[account_id][region].delete_function(self.function_name)

    def create_url_config(self, config: dict[str, Any]) -> FunctionUrlConfig:
        self.url_config = FunctionUrlConfig(function=self, config=config)
        return self.url_config

    def delete_url_config(self) -> None:
        self.url_config = None

    def get_url_config(self) -> FunctionUrlConfig:
        if not self.url_config:
            raise GenericResourcNotFound()
        return self.url_config

    def update_url_config(self, config: dict[str, Any]) -> FunctionUrlConfig:
        self.url_config.update(config)  # type: ignore[union-attr]
        return self.url_config  # type: ignore[return-value]


class FunctionUrlConfig:
    def __init__(self, function: LambdaFunction, config: dict[str, Any]):
        self.function = function
        self.config = config
        self.url = f"https://{random.uuid4().hex}.lambda-url.{function.region}.on.aws"
        self.created = utcnow().strftime("%Y-%m-%dT%H:%M:%S.000+0000")
        self.last_modified = self.created

    def to_dict(self) -> dict[str, Any]:
        return {
            "FunctionUrl": self.url,
            "FunctionArn": self.function.function_arn,
            "AuthType": self.config.get("AuthType"),
            "Cors": self.config.get("Cors"),
            "CreationTime": self.created,
            "LastModifiedTime": self.last_modified,
            "InvokeMode": self.config.get("InvokeMode") or "Buffered",
        }

    def update(self, new_config: dict[str, Any]) -> None:
        if new_config.get("Cors"):
            self.config["Cors"] = new_config["Cors"]
        if new_config.get("AuthType"):
            self.config["AuthType"] = new_config["AuthType"]
        self.last_modified = utcnow().strftime("%Y-%m-%dT%H:%M:%S")


class EventSourceMapping(CloudFormationModel):
    def __init__(self, spec: dict[str, Any]):
        # required
        self.region = spec["RegionName"]
        self.account_id = spec["AccountId"]
        self.uuid = str(random.uuid4())
        self.function_name = spec["FunctionName"]
        self.event_source_arn = spec["EventSourceArn"]
        self.arn: str = make_event_source_mapping_arn(
            self.region, self.account_id, self.uuid
        )

        # optional
        self.batch_size = spec.get("BatchSize")  # type: ignore[assignment]
        self.starting_position = spec.get("StartingPosition")
        if (
            not self.starting_position
            and "sqs" not in self._get_service_source_from_arn()
        ):
            self.starting_position = "TRIM_HORIZON"
        self.enabled = spec.get("Enabled", True)
        self.starting_position_timestamp = spec.get("StartingPositionTimestamp")
        self.kafka_config = spec.get("AmazonManagedKafkaEventSourceConfig")
        self.bisect_on_error = spec.get("BisectBatchOnFunctionError")
        self.destination_config = spec.get("DestinationConfig")
        self.document_db_config = spec.get("DocumentDBEventSourceConfig")
        self.filter_criteria = spec.get("FilterCriteria")
        self.function_response_types = spec.get("FunctionResponseTypes")
        self.kms_key = spec.get("KMSKeyArn")
        self.max_batch_window = spec.get("MaximumBatchingWindowInSeconds")
        self.max_record_age = spec.get("MaximumRecordAgeInSeconds")
        self.max_retry_attempts = spec.get("MaximumRetryAttempts")
        self.metrics = spec.get("MetricsConfig")
        self.parallelization_factor = spec.get("ParallelizationFactor")
        self.poller_config = spec.get("ProvisionedPollerConfig")
        self.queues = spec.get("Queues")
        self.scaling_config = spec.get("ScalingConfig")
        self.self_managed_event_source = spec.get("SelfManagedEventSource")
        self.self_managed_kafka_event_source_config = spec.get(
            "SelfManagedKafkaEventSourceConfig"
        )
        self.source_access_config = spec.get("SourceAccessConfigurations")
        self.tags = spec.get("Tags") or {}
        self.topics = spec.get("Topics")
        self.tumbling_window = spec.get("TumblingWindowInSeconds")

        self.function_arn: str = spec["FunctionArn"]
        self.last_modified = time.mktime(utcnow().timetuple())

    def _get_service_source_from_arn(
        self, event_source_arn: Optional[str] = None
    ) -> str:
        arn = event_source_arn or self.event_source_arn
        service = arn.split(":")[2].lower()
        if service == "sqs" and arn.endswith(".fifo"):
            return "sqs-fifo"
        return service

    @property
    def event_source_arn(self) -> str:
        return self._event_source_arn

    @event_source_arn.setter
    def event_source_arn(self, event_source_arn: str) -> None:
        service = self._get_service_source_from_arn(event_source_arn)
        if service not in ("dynamodb", "kinesis", "sqs", "sqs-fifo"):
            raise ValueError(
                "InvalidParameterValueException", "Unsupported event source type"
            )
        self._event_source_arn = event_source_arn

    @property
    def batch_size(self) -> int:
        return self._batch_size

    @batch_size.setter
    def batch_size(self, new_batch_size: Optional[int]) -> None:
        batch_size_service_map = {
            "kinesis": (100, 10000),
            "dynamodb": (100, 10000),
            "sqs": (10, 10000),
            "sqs-fifo": (10, 10),
        }

        source_type = self._get_service_source_from_arn()
        batch_size_for_source = batch_size_service_map[source_type]

        if new_batch_size is None:
            self._batch_size = batch_size_for_source[0]
        elif new_batch_size > batch_size_for_source[1]:
            error_message = f"BatchSize {new_batch_size} exceeds the max of {batch_size_for_source[1]}"
            raise ValueError("InvalidParameterValueException", error_message)
        else:
            self._batch_size = int(new_batch_size)

    def get_configuration(self) -> dict[str, Any]:
        response_dict = {
            "UUID": self.uuid,
            "BatchSize": self.batch_size,
            "EventSourceArn": self.event_source_arn,
            "EventSourceMappingArn": self.arn,
            "FunctionArn": self.function_arn,
            "LastModified": self.last_modified,
            "LastProcessingResult": None,
            "State": "Enabled" if self.enabled else "Disabled",
            "StateTransitionReason": "User initiated",
            "StartingPosition": self.starting_position,
            "AmazonManagedKafkaEventSourceConfig": self.kafka_config,
            "BisectBatchOnFunctionError": self.bisect_on_error,
            "DestinationConfig": self.destination_config,
            "DocumentDBEventSourceConfig": self.document_db_config,
            "FilterCriteria": self.filter_criteria,
            "FunctionResponseTypes": self.function_response_types,
            "KMSKeyArn": self.kms_key,
            "MaximumBatchingWindowInSeconds": self.max_batch_window,
            "MaximumRecordAgeInSeconds": self.max_record_age,
            "MaximumRetryAttempts": self.max_retry_attempts,
            "MetricsConfig": self.metrics,
            "ParallelizationFactor": self.parallelization_factor,
            "ProvisionedPollerConfig": self.poller_config,
            "Queues": self.queues,
            "ScalingConfig": self.scaling_config,
            "SelfManagedEventSource": self.self_managed_event_source,
            "SelfManagedKafkaEventSourceConfig": self.self_managed_kafka_event_source_config,
            "SourceAccessConfigurations": self.source_access_config,
            "Tags": self.tags,
            "Topics": self.topics,
            "TumblingWindowInSeconds": self.tumbling_window,
        }
        # Only return fields with a value - we don't want to return None for a boolean/int field
        return {k: v for k, v in response_dict.items() if v is not None}

    def delete(self, account_id: str, region_name: str) -> None:
        lambda_backend = lambda_backends[account_id][region_name]
        lambda_backend.delete_event_source_mapping(self.uuid)

    @staticmethod
    def cloudformation_type() -> str:
        # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html
        return "AWS::Lambda::EventSourceMapping"

    @classmethod
    def create_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
        **kwargs: Any,
    ) -> EventSourceMapping:
        properties = cloudformation_json["Properties"]
        lambda_backend = lambda_backends[account_id][region_name]
        return lambda_backend.create_event_source_mapping(properties)

    @classmethod
    def update_from_cloudformation_json(  # type: ignore[misc]
        cls,
        original_resource: Any,
        new_resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
    ) -> EventSourceMapping:
        properties = cloudformation_json["Properties"]
        event_source_uuid = original_resource.uuid
        lambda_backend = lambda_backends[account_id][region_name]
        return lambda_backend.update_event_source_mapping(event_source_uuid, properties)  # type: ignore[return-value]

    @classmethod
    def delete_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
    ) -> None:
        properties = cloudformation_json["Properties"]
        lambda_backend = lambda_backends[account_id][region_name]
        esms = lambda_backend.list_event_source_mappings(
            event_source_arn=properties["EventSourceArn"],
            function_name=properties["FunctionName"],
        )

        for esm in esms:
            if esm.uuid == resource_name:
                esm.delete(account_id, region_name)

    @property
    def physical_resource_id(self) -> str:
        return self.uuid


class LambdaVersion(CloudFormationModel):
    def __init__(self, spec: dict[str, Any]):
        self.version = spec["Version"]

    def __repr__(self) -> str:
        return str(self.logical_resource_id)  # type: ignore[attr-defined]

    @staticmethod
    def cloudformation_type() -> str:
        # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-version.html
        return "AWS::Lambda::Version"

    @classmethod
    def create_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
        **kwargs: Any,
    ) -> LambdaVersion:
        properties = cloudformation_json["Properties"]
        function_name = properties["FunctionName"]
        func = lambda_backends[account_id][region_name].publish_version(function_name)
        spec = {"Version": func.version}  # type: ignore[union-attr]
        return LambdaVersion(spec)


class LambdaStorage:
    def __init__(self, region_name: str, account_id: str):
        # Format 'func_name' {'versions': []}
        self._functions: dict[str, Any] = {}
        self._arns: weakref.WeakValueDictionary[str, LambdaFunction] = (
            weakref.WeakValueDictionary()
        )
        self.region_name = region_name
        self.account_id = account_id
        self.partition = get_partition(region_name)

        # function-arn -> alias -> LambdaAlias
        self._aliases: dict[str, dict[str, LambdaAlias]] = defaultdict(lambda: {})

    def _get_latest(self, name: str) -> LambdaFunction:
        return self._functions[name]["latest"]

    def _get_version(self, name: str, version: str) -> Optional[LambdaFunction]:
        for config in self._functions[name]["versions"]:
            if str(config.version) == version:
                return config

        return None

    def _get_function_aliases(self, function_name: str) -> dict[str, LambdaAlias]:
        fn = self.get_function_by_name_or_arn_with_qualifier(function_name)
        # Split ARN to retrieve an ARN without a qualifier present
        [arn, _, _] = self.split_function_arn(fn.function_arn)
        return self._aliases[arn]

    def delete_alias(self, name: str, function_name: str) -> None:
        aliases = self._get_function_aliases(function_name)
        aliases.pop(name, None)

    def get_alias(self, name: str, function_name: str) -> LambdaAlias:
        aliases = self._get_function_aliases(function_name)
        if name in aliases:
            return aliases[name]

        arn = f"arn:{get_partition(self.region_name)}:lambda:{self.region_name}:{self.account_id}:function:{function_name}:{name}"
        raise UnknownAliasException(arn)

    def put_alias(
        self,
        name: str,
        function_name: str,
        function_version: str,
        description: str,
        routing_config: str,
    ) -> LambdaAlias:
        fn = self.get_function_by_name_or_arn_with_qualifier(
            function_name, function_version
        )
        aliases = self._get_function_aliases(function_name)
        if name in aliases:
            arn = f"arn:{get_partition(self.region_name)}:lambda:{self.region_name}:{self.account_id}:function:{function_name}:{name}"
            raise ConflictException(f"Alias already exists: {arn}")

        alias = LambdaAlias(
            account_id=self.account_id,
            region=self.region_name,
            name=name,
            function_name=fn.function_name,
            function_version=function_version,
            description=description,
            routing_config=routing_config,
        )
        aliases[name] = alias
        return alias

    def update_alias(
        self,
        name: str,
        function_name: str,
        function_version: str,
        description: str,
        routing_config: str,
    ) -> LambdaAlias:
        alias = self.get_alias(name, function_name)

        # errors if new function version doesn't exist
        self.get_function_by_name_or_arn_with_qualifier(function_name, function_version)

        alias.update(description, function_version, routing_config)
        return alias

    def get_function_by_name_forbid_qualifier(self, name: str) -> LambdaFunction:
        """
        Get function by name forbidding a qualifier
        :raises: UnknownFunctionException if function not found
        :raises: InvalidParameterValue if qualifier is provided
        """

        if name.count(":") == 1:
            raise InvalidParameterValueException("Cannot provide qualifier")

        if name not in self._functions:
            raise self.construct_unknown_function_exception(name)

        return self._get_latest(name)

    def get_function_by_name_with_qualifier(
        self, name: str, qualifier: Optional[str] = None
    ) -> LambdaFunction:
        """
        Get function by name with an optional qualifier
        :raises: UnknownFunctionException if function not found
        """

        # Function name may contain an alias
        # <fn_name>:<alias_name>
        if ":" in name:
            # Prefer qualifier in name over qualifier arg
            [name, qualifier] = name.split(":")

        # Find without qualifier
        if qualifier is None:
            return self.get_function_by_name_forbid_qualifier(name)

        if name not in self._functions:
            raise self.construct_unknown_function_exception(name, qualifier)

        # Find by latest
        if qualifier.lower() == "$latest":
            return self._functions[name]["latest"]

        # Find by version
        found_version = self._get_version(name, qualifier)
        if found_version:
            return found_version

        # Find by alias
        aliases = self._get_function_aliases(name)
        if qualifier in aliases:
            alias_version = aliases[qualifier].function_version

            # Find by alias pointing to latest
            if alias_version.lower() == "$latest":
                return self._functions[name]["latest"]

            # Find by alias pointing to version
            found_alias = self._get_version(name, alias_version)
            if found_alias:
                return found_alias

        raise self.construct_unknown_function_exception(name, qualifier)

    def list_versions_by_function(self, name: str) -> Iterable[LambdaFunction]:
        if name not in self._functions:
            return []

        latest = copy.copy(self._functions[name]["latest"])
        latest.function_arn += ":$LATEST"
        return [latest] + self._functions[name]["versions"]

    def list_aliases(self, function_name: str) -> Iterable[LambdaAlias]:
        aliases = self._get_function_aliases(function_name)
        return sorted(aliases.values(), key=lambda alias: alias.name)

    def get_arn(self, arn: str) -> Optional[LambdaFunction]:
        [arn_without_qualifier, _, _] = self.split_function_arn(arn)
        return self._arns.get(arn_without_qualifier, None)

    def split_function_arn(self, arn: str) -> tuple[str, str, Optional[str]]:
        """
        Handy utility to parse an ARN into:
        - ARN without qualifier
        - Function name
        - Optional qualifier
        """
        qualifier = None
        # Function ARN may contain an alias
        # arn:aws:lambda:region:account_id:function:<fn_name>:<alias_name>
        if ":" in arn.split(":function:")[-1]:
            qualifier = arn.split(":")[-1]
            # arn = arn:aws:lambda:region:account_id:function:<fn_name>
            arn = ":".join(arn.split(":")[0:-1])
        name = arn.split(":")[-1]
        return arn, name, qualifier

    def get_function_by_name_or_arn_forbid_qualifier(
        self, name_or_arn: str
    ) -> LambdaFunction:
        """
        Get function by name or arn forbidding a qualifier
        :raises: UnknownFunctionException if function not found
        :raises: InvalidParameterValue if qualifier is provided
        """

        if re.match(ARN_PARTITION_REGEX, name_or_arn):
            [_, name, qualifier] = self.split_function_arn(name_or_arn)

            if qualifier is not None:
                raise InvalidParameterValueException("Cannot provide qualifier")

            return self.get_function_by_name_forbid_qualifier(name)
        else:
            # name_or_arn is not an arn
            return self.get_function_by_name_forbid_qualifier(name_or_arn)

    def get_function_by_name_or_arn_with_qualifier(
        self, name_or_arn: str, qualifier: Optional[str] = None
    ) -> LambdaFunction:
        """
        Get function by name or arn with an optional qualifier
        :raises: UnknownFunctionException if function not found
        """

        if re.match(ARN_PARTITION_REGEX, name_or_arn):
            [_, name, qualifier_in_arn] = self.split_function_arn(name_or_arn)
            return self.get_function_by_name_with_qualifier(
                name, qualifier_in_arn or qualifier
            )
        else:
            return self.get_function_by_name_with_qualifier(name_or_arn, qualifier)

    def construct_unknown_function_exception(
        self, name_or_arn: str, qualifier: Optional[str] = None
    ) -> UnknownFunctionException:
        if re.match(ARN_PARTITION_REGEX, name_or_arn):
            arn = name_or_arn
        else:
            # name_or_arn is a function name with optional qualifier <func_name>[:<qualifier>]
            arn = make_function_arn(self.region_name, self.account_id, name_or_arn)
            # Append explicit qualifier to arn only if the name doesn't already have it
            if qualifier and ":" not in name_or_arn:
                arn = f"{arn}:{qualifier}"
        return UnknownFunctionException(arn)

    def put_function(self, fn: LambdaFunction) -> None:
        valid_role = re.match(InvalidRoleFormat.pattern, fn.role)
        if valid_role:
            account = valid_role.group(2)
            if account != self.account_id:
                raise CrossAccountNotAllowed()
            try:
                iam_backend = iam_backends[self.account_id][self.partition]
                iam_backend.get_role_by_arn(fn.role)
            except IAMNotFoundException:
                raise InvalidParameterValueException(
                    "The role defined for the function cannot be assumed by Lambda."
                )
        else:
            raise InvalidRoleFormat(fn.role)
        if fn.function_name in self._functions:
            self._functions[fn.function_name]["latest"] = fn
        else:
            self._functions[fn.function_name] = {"latest": fn, "versions": []}
        self._arns[fn.function_arn] = fn

    def publish_version(
        self, name_or_arn: str, description: str = ""
    ) -> Optional[LambdaFunction]:
        function = self.get_function_by_name_or_arn_forbid_qualifier(name_or_arn)
        name = function.function_name
        if name not in self._functions:
            return None
        if not self._functions[name]["latest"]:
            return None

        all_versions = self._functions[name]["versions"]
        if all_versions:
            latest_published = all_versions[-1]
            if not function.code_or_config_updated:
                # Nothing has changed, don't publish
                return latest_published
            else:
                function.code_or_config_updated = False

        new_version = len(all_versions) + 1
        fn = copy.copy(self._functions[name]["latest"])
        fn.set_version(new_version)
        if description:
            fn.description = description

        self._functions[name]["versions"].append(fn)
        self._arns[fn.function_arn] = fn
        return fn

    def del_function(self, name_or_arn: str, qualifier: Optional[str] = None) -> None:
        # Qualifier may be explicitly passed or part of function name or ARN, extract it here
        if re.match(ARN_PARTITION_REGEX, name_or_arn):
            # Extract from ARN
            if ":" in name_or_arn.split(":function:")[-1]:
                qualifier = name_or_arn.split(":")[-1]
        else:
            # Extract from function name
            if ":" in name_or_arn:
                qualifier = name_or_arn.split(":")[1]

        function = self.get_function_by_name_or_arn_with_qualifier(
            name_or_arn, qualifier
        )
        name = function.function_name
        if not qualifier:
            # Something is still reffing this so delete all arns
            latest = self._functions[name]["latest"].function_arn
            del self._arns[latest]

            for fn in self._functions[name]["versions"]:
                del self._arns[fn.function_arn]

            del self._functions[name]

        else:
            if qualifier == "$LATEST":
                self._functions[name]["latest"] = None
            else:
                self._functions[name]["versions"].remove(function)

            # If theres no functions left
            if (
                not self._functions[name]["versions"]
                and not self._functions[name]["latest"]
            ):
                del self._functions[name]

        self._aliases[function.function_arn] = {}

    def all(self) -> Iterable[LambdaFunction]:
        result = []

        for function_group in list(self._functions.values()):
            latest = copy.deepcopy(function_group["latest"])
            latest.function_arn = f"{latest.function_arn}:$LATEST"
            result.append(latest)

            result.extend(function_group["versions"])

        return result

    def latest(self) -> Iterable[LambdaFunction]:
        """
        Return the list of functions with version @LATEST
        :return:
        """
        result = []
        for function_group in self._functions.values():
            if function_group["latest"] is not None:
                result.append(function_group["latest"])

        return result


class LayerStorage:
    def __init__(self) -> None:
        self._layers: dict[str, Layer] = {}
        self._arns: weakref.WeakValueDictionary[str, LambdaFunction] = (
            weakref.WeakValueDictionary()
        )

    def _find_layer_by_name_or_arn(self, name_or_arn: str) -> Layer:
        if name_or_arn in self._layers:
            return self._layers[name_or_arn]
        for layer in self._layers.values():
            if layer.layer_arn == name_or_arn:
                return layer
        raise UnknownLayerException()

    def put_layer_version(self, layer_version: LayerVersion) -> None:
        """
        :param layer_version: LayerVersion
        """
        if layer_version.name not in self._layers:
            self._layers[layer_version.name] = Layer(layer_version)
        self._layers[layer_version.name].attach_version(layer_version)

    def list_layers(self) -> Iterable[dict[str, Any]]:
        return [
            layer.to_dict() for layer in self._layers.values() if layer.layer_versions
        ]

    def delete_layer_version(self, layer_name: str, layer_version: str) -> None:
        layer = self._find_layer_by_name_or_arn(layer_name)
        layer.delete_version(layer_version)

    def get_layer_version(self, layer_name: str, layer_version: str) -> LayerVersion:
        layer = self._find_layer_by_name_or_arn(layer_name)
        for lv in layer.layer_versions.values():
            if lv.version == int(layer_version):
                return lv
        raise UnknownLayerException()

    def get_layer_versions(self, layer_name: str) -> list[LayerVersion]:
        if layer_name in self._layers:
            return list(iter(self._layers[layer_name].layer_versions.values()))
        return []

    def get_layer_version_by_arn(
        self, layer_version_arn: str
    ) -> Optional[LayerVersion]:
        split_arn = split_layer_arn(layer_version_arn)
        if split_arn.layer_name in self._layers:
            return self._layers[split_arn.layer_name].layer_versions.get(
                split_arn.version, None
            )
        return None


class LambdaBackend(BaseBackend):
    """
    Implementation of the AWS Lambda endpoint.
    Invoking functions is supported - they will run inside a Docker container, emulating the real AWS behaviour as closely as possible.

    .. warning:: When invoking a function using the decorators, the created Docker container cannot reach Moto (or it's in-memory state). Any AWS SDK-requests within your Lambda will try to connect to AWS instead.

    It is possible to connect from AWS Lambdas to other services, as long as you are running MotoProxy or the MotoServer in a Docker container.

    When running the MotoProxy, calls to other AWS services are automatically proxied.

    When running MotoServer, the Lambda has access to environment variables `MOTO_HOST` and `MOTO_PORT`, which can be used to build the url that MotoServer runs on:

    .. sourcecode:: python

        def lambda_handler(event, context):
            host = os.environ.get("MOTO_HOST")
            port = os.environ.get("MOTO_PORT")
            url = host + ":" + port
            ec2 = boto3.client('ec2', region_name='us-west-2', endpoint_url=url)

            # Or even simpler:
            full_url = os.environ.get("MOTO_HTTP_ENDPOINT")
            ec2 = boto3.client("ec2", region_name="eu-west-1", endpoint_url=full_url)

            ec2.do_whatever_inside_the_existing_moto_server()

    Moto will run on port 5000 by default. This can be overwritten by setting an environment variable when starting Moto:

    .. sourcecode:: bash

        # This env var will be propagated to the Docker container running the Lambda functions
        MOTO_PORT=5000 moto_server

    The Docker container uses the default network mode, `bridge`.
    The following environment variables are available for fine-grained control over the Docker connection options:

    .. sourcecode:: bash

        # Provide the name of a custom network to connect to
        MOTO_DOCKER_NETWORK_NAME=mycustomnetwork moto_server

        # Override the network mode
        # For example, network_mode=host would use the network of the host machine
        # Note that this option will be ignored if MOTO_DOCKER_NETWORK_NAME is also set
        MOTO_DOCKER_NETWORK_MODE=host moto_server

    _-_-_-_

    The Docker images used by Moto are taken from the following repositories:

    - `mlupin/docker-lambda` (for recent versions)
    - `lambci/lambda` (for older/outdated versions)

    Use the following environment variable to configure Moto to look for images in an additional repository:

    .. sourcecode:: bash

        MOTO_DOCKER_LAMBDA_IMAGE=mlupin/docker-lambda

    _-_-_-_

    Use the following environment variable if you want to configure the data directory used by the Docker containers:

    .. sourcecode:: bash

        MOTO_LAMBDA_DATA_DIR=/tmp/data

    _-_-_-_

    If you want to mock the Lambda-containers invocation without starting a Docker-container, use the simple decorator:

    .. sourcecode:: python

        @mock_aws(config={"lambda": {"use_docker": False}})

    """

    def __init__(self, region_name: str, account_id: str):
        super().__init__(region_name, account_id)
        self._lambdas = LambdaStorage(region_name=region_name, account_id=account_id)
        self._event_source_mappings: dict[str, EventSourceMapping] = {}
        self._layers = LayerStorage()

    def create_alias(
        self,
        name: str,
        function_name: str,
        function_version: str,
        description: str,
        routing_config: str,
    ) -> LambdaAlias:
        return self._lambdas.put_alias(
            name, function_name, function_version, description, routing_config
        )

    def delete_alias(self, name: str, function_name: str) -> None:
        return self._lambdas.delete_alias(name, function_name)

    def get_alias(self, name: str, function_name: str) -> LambdaAlias:
        return self._lambdas.get_alias(name, function_name)

    def update_alias(
        self,
        name: str,
        function_name: str,
        function_version: str,
        description: str,
        routing_config: str,
    ) -> LambdaAlias:
        """
        The RevisionId parameter is not yet implemented
        """
        return self._lambdas.update_alias(
            name, function_name, function_version, description, routing_config
        )

    def create_function(self, spec: dict[str, Any]) -> LambdaFunction:
        """
        The Code.ImageUri is not validated by default. Set environment variable MOTO_LAMBDA_STUB_ECR=false if you want to validate the image exists in our mocked ECR.
        """
        function_name = spec.get("FunctionName", None)
        if function_name is None:
            raise RESTError("InvalidParameterValueException", "Missing FunctionName")

        fn = LambdaFunction(
            account_id=self.account_id,
            spec=spec,
            region=self.region_name,
            version="$LATEST",
        )

        self._lambdas.put_function(fn)

        if spec.get("Publish"):
            ver = self.publish_version(function_name)
            fn = copy.deepcopy(
                fn
            )  # We don't want to change the actual version - just the return value
            fn.version = ver.version  # type: ignore[union-attr]
        return fn

    def create_function_url_config(
        self, name_or_arn: str, config: dict[str, Any]
    ) -> FunctionUrlConfig:
        """
        The Qualifier-parameter is not yet implemented.
        Function URLs are not yet mocked, so invoking them will fail
        """
        function = self._lambdas.get_function_by_name_or_arn_forbid_qualifier(
            name_or_arn
        )
        return function.create_url_config(config)

    def delete_function_url_config(self, name_or_arn: str) -> None:
        """
        The Qualifier-parameter is not yet implemented
        """
        function = self._lambdas.get_function_by_name_or_arn_forbid_qualifier(
            name_or_arn
        )
        function.delete_url_config()

    def get_function_url_config(self, name_or_arn: str) -> FunctionUrlConfig:
        """
        The Qualifier-parameter is not yet implemented
        """
        function = self._lambdas.get_function_by_name_or_arn_forbid_qualifier(
            name_or_arn
        )
        if not function:
            raise UnknownFunctionException(arn=name_or_arn)
        return function.get_url_config()

    def update_function_url_config(
        self, name_or_arn: str, config: dict[str, Any]
    ) -> FunctionUrlConfig:
        """
        The Qualifier-parameter is not yet implemented
        """
        function = self._lambdas.get_function_by_name_or_arn_forbid_qualifier(
            name_or_arn
        )
        return function.update_url_config(config)

    def create_event_source_mapping(self, spec: dict[str, Any]) -> EventSourceMapping:
        required = ["EventSourceArn", "FunctionName"]
        for param in required:
            if not spec.get(param):
                raise RESTError("InvalidParameterValueException", f"Missing {param}")
        spec["RegionName"] = self.region_name
        spec["AccountId"] = self.account_id

        # Validate function name
        func = self._lambdas.get_function_by_name_or_arn_with_qualifier(
            spec.get("FunctionName", "")
        )

        # Validate queue
        sqs_backend = sqs_backends[self.account_id][self.region_name]
        for queue in sqs_backend.queues.values():
            if queue.queue_arn == spec["EventSourceArn"]:
                if queue.lambda_event_source_mappings.get("func.function_arn"):
                    # TODO: Correct exception?
                    raise RESTError(
                        "ResourceConflictException", "The resource already exists."
                    )
                spec.update({"FunctionArn": func.function_arn})
                esm = EventSourceMapping(spec)
                self._event_source_mappings[esm.uuid] = esm

                # Set backend function on queue
                queue.lambda_event_source_mappings[esm.function_arn] = esm

                return esm

        ddbstream_backend = dynamodbstreams_backends[self.account_id][self.region_name]
        ddb_backend = dynamodb_backends[self.account_id][self.region_name]
        for ddbstream in ddbstream_backend.list_streams():
            if ddbstream["StreamArn"] == spec["EventSourceArn"]:
                spec.update({"FunctionArn": func.function_arn})
                esm = EventSourceMapping(spec)
                self._event_source_mappings[esm.uuid] = esm
                table_name = ddbstream["TableName"]
                table = ddb_backend.get_table(table_name)
                table.lambda_event_source_mappings[esm.function_arn] = esm
                return esm

        kinesis_backend: KinesisBackend = kinesis_backends[self.account_id][
            self.region_name
        ]
        for stream in kinesis_backend.streams.values():
            if stream.arn == spec["EventSourceArn"]:
                spec.update({"FunctionArn": func.function_arn})
                esm = EventSourceMapping(spec)
                self._event_source_mappings[esm.uuid] = esm
                stream.lambda_event_source_mappings[esm.event_source_arn] = esm
                return esm

        raise RESTError("ResourceNotFoundException", "Invalid EventSourceArn")

    def publish_layer_version(self, spec: dict[str, Any]) -> LayerVersion:
        required = ["LayerName", "Content"]
        for param in required:
            if not spec.get(param):
                raise InvalidParameterValueException(f"Missing {param}")
        layer_version = LayerVersion(
            spec, account_id=self.account_id, region=self.region_name
        )
        self._layers.put_layer_version(layer_version)
        return layer_version

    def list_layers(self) -> Iterable[dict[str, Any]]:
        return self._layers.list_layers()

    def delete_layer_version(self, layer_name: str, layer_version: str) -> None:
        return self._layers.delete_layer_version(layer_name, layer_version)

    def get_layer_version(self, layer_name: str, layer_version: str) -> LayerVersion:
        return self._layers.get_layer_version(layer_name, layer_version)

    def list_layer_versions(self, layer_name: str) -> Iterable[LayerVersion]:
        return self._layers.get_layer_versions(layer_name)

    def layers_versions_by_arn(self, layer_version_arn: str) -> Optional[LayerVersion]:
        return self._layers.get_layer_version_by_arn(layer_version_arn)

    def publish_version(
        self, function_name: str, description: str = ""
    ) -> Optional[LambdaFunction]:
        return self._lambdas.publish_version(function_name, description)

    def get_function(
        self, function_name_or_arn: str, qualifier: Optional[str] = None
    ) -> LambdaFunction:
        return self._lambdas.get_function_by_name_or_arn_with_qualifier(
            function_name_or_arn, qualifier
        )

    def list_versions_by_function(self, function_name: str) -> Iterable[LambdaFunction]:
        return self._lambdas.list_versions_by_function(function_name)

    def list_aliases(self, function_name: str) -> Iterable[LambdaAlias]:
        return self._lambdas.list_aliases(function_name)

    def get_event_source_mapping(self, uuid: str) -> Optional[EventSourceMapping]:
        return self._event_source_mappings.get(uuid)

    def delete_event_source_mapping(self, uuid: str) -> Optional[EventSourceMapping]:
        return self._event_source_mappings.pop(uuid, None)

    def update_event_source_mapping(
        self, uuid: str, spec: dict[str, Any]
    ) -> Optional[EventSourceMapping]:
        esm = self.get_event_source_mapping(uuid)
        if not esm:
            return None

        for key in spec.keys():
            if key == "FunctionName":
                func = self._lambdas.get_function_by_name_or_arn_with_qualifier(
                    spec[key]
                )
                esm.function_arn = func.function_arn
            elif key == "BatchSize":
                esm.batch_size = spec[key]
            elif key == "Enabled":
                esm.enabled = spec[key]
            elif key == "FilterCriteria":
                esm.filter_criteria = spec[key]
            elif key == "MaximumBatchingWindowInSeconds":
                esm.max_batch_window = spec[key]
            elif key == "ParallelizationFactor":
                esm.parallelization_factor = spec[key]
            elif key == "DestinationConfig":
                esm.destination_config = spec[key]
            elif key == "MaximumRecordAgeInSeconds":
                esm.max_record_age = spec[key]
            elif key == "BisectBatchOnFunctionError":
                esm.bisect_on_error = spec[key]
            elif key == "MaximumRetryAttempts":
                esm.max_retry_attempts = spec[key]
            elif key == "TumblingWindowInSeconds":
                esm.tumbling_window = spec[key]
            elif key == "SourceAccessConfigurations":
                esm.source_access_config = spec[key]
            elif key == "FunctionResponseTypes":
                esm.function_response_types = spec[key]
            elif key == "ScalingConfig":
                esm.scaling_config = spec[key]
            elif key == "DocumentDBEventSourceConfig":
                esm.document_db_config = spec[key]
            elif key == "KMSKeyArn":
                esm.kms_key = spec[key]
            elif key == "MetricsConfig":
                esm.metrics = spec[key]
            elif key == "ProvisionedPollerConfig":
                esm.poller_config = spec[key]

        esm.last_modified = time.mktime(utcnow().timetuple())
        return esm

    def list_event_source_mappings(
        self, event_source_arn: str, function_name: str
    ) -> Iterable[EventSourceMapping]:
        esms = list(self._event_source_mappings.values())
        if event_source_arn:
            esms = list(filter(lambda x: x.event_source_arn == event_source_arn, esms))
        if function_name:
            esms = list(filter(lambda x: x.function_name == function_name, esms))
        return esms

    def get_function_by_arn(self, function_arn: str) -> Optional[LambdaFunction]:
        return self._lambdas.get_arn(function_arn)

    def delete_function(
        self, function_name: str, qualifier: Optional[str] = None
    ) -> None:
        self._lambdas.del_function(function_name, qualifier)

    def list_functions(
        self, func_version: Optional[str] = None
    ) -> Iterable[LambdaFunction]:
        if func_version == "ALL":
            return self._lambdas.all()
        return self._lambdas.latest()

    def send_sqs_batch(self, function_arn: str, messages: Any, queue_arn: str) -> bool:
        success = True
        for message in messages:
            result = self._send_sqs_message(function_arn, message, queue_arn)
            if not result:
                success = False
        return success

    def _send_sqs_message(
        self, function_arn: str, message: Any, queue_arn: str
    ) -> bool:
        event = {
            "Records": [
                {
                    "messageId": message.id,
                    "receiptHandle": message.receipt_handle,
                    "body": message.body,
                    "attributes": {
                        "ApproximateReceiveCount": "1",
                        "SentTimestamp": "1545082649183",
                        "SenderId": "AIDAIENQZJOLO23YVJ4VO",
                        "ApproximateFirstReceiveTimestamp": "1545082649185",
                    },
                    "messageAttributes": {},
                    "md5OfBody": "098f6bcd4621d373cade4e832627b4f6",
                    "eventSource": "aws:sqs",
                    "eventSourceARN": queue_arn,
                    "awsRegion": self.region_name,
                }
            ]
        }
        if queue_arn.endswith(".fifo"):
            # Messages from FIFO queue have additional attributes
            event["Records"][0]["attributes"].update(
                {
                    "MessageGroupId": message.group_id,
                    "MessageDeduplicationId": message.deduplication_id,
                }
            )

        request_headers: dict[str, Any] = {}
        response_headers: dict[str, Any] = {}
        self.invoke(
            function_name=function_arn,
            qualifier=None,
            body=json.dumps(event),
            headers=request_headers,
            response_headers=response_headers,
        )
        return "x-amz-function-error" not in response_headers

    def send_kinesis_message(
        self,
        function_name: str,
        kinesis_stream: str,
        kinesis_partition_key: str,
        kinesis_sequence_number: str,
        kinesis_data: str,
        kinesis_shard_id: str,
    ) -> None:
        func = self._lambdas.get_function_by_name_or_arn_with_qualifier(
            function_name, qualifier=None
        )
        event = {
            "Records": [
                {
                    "kinesis": {
                        "kinesisSchemaVersion": "1.0",
                        "partitionKey": kinesis_partition_key,
                        "sequenceNumber": kinesis_sequence_number,
                        "data": kinesis_data,
                        "approximateArrivalTimestamp": round(time.time(), 3),
                    },
                    "eventSource": "aws:kinesis",
                    "eventVersion": "1.0",
                    "eventID": f"{kinesis_shard_id}:{kinesis_sequence_number}",
                    "eventName": "aws:kinesis:record",
                    "invokeIdentityArn": func.role,
                    "awsRegion": self.region_name,
                    "eventSourceARN": kinesis_stream,
                }
            ]
        }
        func.invoke(json.dumps(event), {}, {})

    def send_sns_message(
        self,
        function_name: str,
        message: str,
        subject: Optional[str] = None,
        qualifier: Optional[str] = None,
    ) -> None:
        event = {
            "Records": [
                {
                    "EventVersion": "1.0",
                    "EventSubscriptionArn": "arn:aws:sns:EXAMPLE",
                    "EventSource": "aws:sns",
                    "Sns": {
                        "SignatureVersion": "1",
                        "Timestamp": "1970-01-01T00:00:00.000Z",
                        "Signature": "EXAMPLE",
                        "SigningCertUrl": "EXAMPLE",
                        "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
                        "Message": message,
                        "MessageAttributes": {
                            "Test": {"Type": "String", "Value": "TestString"},
                            "TestBinary": {"Type": "Binary", "Value": "TestBinary"},
                        },
                        "Type": "Notification",
                        "UnsubscribeUrl": "EXAMPLE",
                        "TopicArn": "arn:aws:sns:EXAMPLE",
                        "Subject": subject or "TestInvoke",
                    },
                }
            ]
        }
        func = self._lambdas.get_function_by_name_or_arn_with_qualifier(
            function_name, qualifier
        )
        func.invoke(json.dumps(event), {}, {})

    def send_dynamodb_items(
        self, function_arn: str, items: list[Any], source: str
    ) -> Union[str, bytes]:
        event = {
            "Records": [
                {
                    "eventID": item.to_json()["eventID"],
                    "eventName": item.to_json()["eventName"],
                    "eventVersion": item.to_json()["eventVersion"],
                    "eventSource": item.to_json()["eventSource"],
                    "awsRegion": self.region_name,
                    "dynamodb": item.to_json()["dynamodb"],
                    "eventSourceARN": source,
                }
                for item in items
            ]
        }
        func = self._lambdas.get_arn(function_arn)
        return func.invoke(json.dumps(event), {}, {})  # type: ignore[union-attr]

    def send_log_event(
        self,
        function_arn: str,
        filter_name: str,
        log_group_name: str,
        log_stream_name: str,
        log_events: Any,
    ) -> None:
        data = {
            "messageType": "DATA_MESSAGE",
            "owner": self.account_id,
            "logGroup": log_group_name,
            "logStream": log_stream_name,
            "subscriptionFilters": [filter_name],
            "logEvents": log_events,
        }

        output = io.BytesIO()
        with GzipFile(fileobj=output, mode="w") as f:
            f.write(json.dumps(data, separators=(",", ":")).encode("utf-8"))
        payload_gz_encoded = base64.b64encode(output.getvalue()).decode("utf-8")

        event = {"awslogs": {"data": payload_gz_encoded}}

        func = self._lambdas.get_arn(function_arn)
        func.invoke(json.dumps(event), {}, {})  # type: ignore[union-attr]

    def _get_resource_by_arn(self, arn: str) -> EventSourceMapping | LambdaFunction:
        arn_breakdown = arn.split(":")
        resource_type = arn_breakdown[len(arn_breakdown) - 2]
        resource_name = arn_breakdown[len(arn_breakdown) - 1]
        if resource_type == "event-source-mapping":
            esm = self._event_source_mappings.get(resource_name)
            if not esm:
                raise RESTError(
                    "ResourceNotFoundException",
                    f"Event source mapping {resource_name} not found.",
                )
            return esm
        return self._lambdas.get_function_by_name_or_arn_with_qualifier(arn)

    def list_tags(self, resource_arn: str) -> dict[str, str]:
        resource = self._get_resource_by_arn(resource_arn)
        return resource.tags

    def tag_resource(self, resource_arn: str, tags: dict[str, str]) -> None:
        resource = self._get_resource_by_arn(resource_arn)
        resource.tags.update(tags)

    def untag_resource(self, resource_arn: str, tagKeys: list[str]) -> None:
        resource = self._get_resource_by_arn(resource_arn)
        for key in tagKeys:
            resource.tags.pop(key, None)

    def add_permission(
        self, function_name: str, qualifier: str, raw: str
    ) -> dict[str, Any]:
        fn = self.get_function(function_name, qualifier)
        statement, revision = fn.policy.add_statement(raw, qualifier)
        return statement

    def remove_permission(
        self, function_name: str, sid: str, revision: str = ""
    ) -> None:
        fn = self.get_function(function_name)
        fn.policy.del_statement(sid, revision)

    def get_function_code_signing_config(self, function_name: str) -> dict[str, Any]:
        fn = self.get_function(function_name)
        return fn.get_function_code_signing_config()

    def get_policy(self, function_name: str, qualifier: Optional[str] = None) -> str:
        fn = self._lambdas.get_function_by_name_or_arn_with_qualifier(
            function_name, qualifier
        )
        return fn.policy.wire_format()

    def update_function_code(
        self, function_name: str, qualifier: str, body: dict[str, Any]
    ) -> Optional[dict[str, Any]]:
        fn: LambdaFunction = self.get_function(function_name, qualifier)
        fn.update_function_code(body)

        if body.get("Publish", False):
            fn = self.publish_version(function_name)  # type: ignore[assignment]

        return fn.update_function_code(body)

    def update_function_configuration(
        self, function_name: str, qualifier: str, body: dict[str, Any]
    ) -> Optional[dict[str, Any]]:
        fn = self.get_function(function_name, qualifier)

        return fn.update_configuration(body)

    def invoke(
        self,
        function_name: str,
        qualifier: Optional[str],
        body: Any,
        headers: Any,
        response_headers: Any,
    ) -> Optional[Union[str, bytes]]:
        """
        Invoking a Function with PackageType=Image is not yet supported.

        Invoking a Function against Lambda without docker now supports customised responses, the default being `Simple Lambda happy path OK`.
        You can use a dedicated API to override this, by configuring a queue of expected results.

        A request to `invoke` will take the first result from that queue.

        Configure this queue by making an HTTP request to `/moto-api/static/lambda-simple/response`. An example invocation looks like this:

        .. sourcecode:: python

            expected_results = {"results": ["test", "test 2"], "region": "us-east-1"}
            resp = requests.post(
                "http://motoapi.amazonaws.com/moto-api/static/lambda-simple/response",
                json=expected_results
            )
            assert resp.status_code == 201

            client = boto3.client("lambda", region_name="us-east-1")
            resp = client.invoke(...) # resp["Payload"].read().decode() == "test"
            resp = client.invoke(...) # resp["Payload"].read().decode() == "test2"
        """
        fn = self.get_function(function_name, qualifier)
        payload = fn.invoke(body, headers, response_headers)
        response_headers["Content-Length"] = str(len(payload))
        return payload

    def put_function_concurrency(
        self, function_name: str, reserved_concurrency: str
    ) -> str:
        """Establish concurrency limit/reservations for a function

        Actual lambda restricts concurrency to 1000 (default) per region/account
        across all functions; we approximate that behavior by summing across all
        functions (hopefully all in the same account and region) and allowing the
        caller to simulate an increased quota.

        By default, no quota is enforced in order to preserve compatibility with
        existing code that assumes it can do as many things as it likes. To model
        actual AWS behavior, define the MOTO_LAMBDA_CONCURRENCY_QUOTA environment
        variable prior to testing.
        """

        quota: Optional[str] = os.environ.get("MOTO_LAMBDA_CONCURRENCY_QUOTA")
        if quota is not None:
            # Enforce concurrency limits as described above
            available = int(quota) - int(reserved_concurrency)
            for fnx in self.list_functions():
                if fnx.reserved_concurrency and fnx.function_name != function_name:
                    available -= int(fnx.reserved_concurrency)
            if available < 100:
                raise InvalidParameterValueException(
                    "Specified ReservedConcurrentExecutions for function decreases account's UnreservedConcurrentExecution below its minimum value of [100]."
                )

        fn = self.get_function(function_name)
        fn.reserved_concurrency = reserved_concurrency
        return fn.reserved_concurrency

    def delete_function_concurrency(self, function_name: str) -> Optional[str]:
        fn = self.get_function(function_name)
        fn.reserved_concurrency = None
        return fn.reserved_concurrency

    def get_function_concurrency(self, function_name: str) -> Optional[str]:
        fn = self.get_function(function_name)
        return fn.reserved_concurrency

    def put_function_event_invoke_config(
        self, function_name: str, config: dict[str, Any]
    ) -> dict[str, Any]:
        fn = self.get_function(function_name)
        event_config = EventInvokeConfig(fn.function_arn, fn.last_modified, config)
        fn.event_invoke_config.append(event_config)
        return event_config.response()

    def update_function_event_invoke_config(
        self, function_name: str, config: dict[str, Any]
    ) -> dict[str, Any]:
        # partial functionality, the update function just does a put
        # instead of partial update
        return self.put_function_event_invoke_config(function_name, config)

    def get_function_event_invoke_config(self, function_name: str) -> dict[str, Any]:
        fn = self.get_function(function_name)
        if fn.event_invoke_config:
            response = fn.event_invoke_config[0]
            return response.response()
        else:
            raise UnknownEventConfig(fn.function_arn)

    def delete_function_event_invoke_config(self, function_name: str) -> None:
        if self.get_function_event_invoke_config(function_name):
            fn = self.get_function(function_name)
            fn.event_invoke_config = []

    def list_function_event_invoke_configs(self, function_name: str) -> dict[str, Any]:
        response: dict[str, list[dict[str, Any]]] = {"FunctionEventInvokeConfigs": []}
        try:
            response["FunctionEventInvokeConfigs"] = [
                self.get_function_event_invoke_config(function_name)
            ]
            return response
        except UnknownEventConfig:
            return response

    def add_layer_version_permission(
        self, layer_name: str, version_number: int, statement: str
    ) -> tuple[str, str]:
        layer_version = self.get_layer_version(layer_name, str(version_number))
        return layer_version.policy.add_statement(statement)

    def get_layer_version_policy(self, layer_name: str, version_number: int) -> str:
        layer_version = self.get_layer_version(layer_name, str(version_number))
        return layer_version.policy.wire_format()

    def remove_layer_version_permission(
        self, layer_name: str, version_number: str, sid: str, revision: str = ""
    ) -> None:
        layer_version = self.get_layer_version(layer_name, str(version_number))
        layer_version.policy.del_statement(sid, revision)


def do_validate_s3() -> bool:
    return os.environ.get("VALIDATE_LAMBDA_S3", "") in ["", "1", "true"]


lambda_backends = BackendDict(LambdaBackend, "lambda")